You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GSON实现Java对象与指定JSON互转及目标字段提取问题

如何用Gson实现指定JSON与Java对象的互转并提取目标字段?

我来帮你解决这个问题!你的核心问题是Java类的结构和JSON的层级不匹配,而且没有正确定义需要提取的字段。我们一步步来修正:

1. 修正Java类结构

首先看你的JSON结构:

{
"waypoints": [
{
"waypoint_index": 0,
...
"location": [28.068655, 41.180774]
},
...
]
}

这里的waypoints是数组类型(对应Java的List),数组里的每个元素是一个包含waypoint_index和location的对象。你原来的类结构把waypoints当成了单个对象,这是错误的。

我们只需要定义我们关心的字段,Gson会自动忽略JSON中未定义的字段(比如hint、name)。正确的类结构如下:

import java.util.List;

// 对应最外层的JSON对象
public class ResultOsrm {
    // waypoints是数组,所以用List<Waypoint>
    public List<Waypoint> waypoints;
}

// 对应waypoints数组里的每个元素对象
public class Waypoint {
    // 对应JSON中的waypoint_index字段
    public int waypoint_index;
    // location是数值数组,用List<Double>接收(也可以用double[])
    public List<Double> location;
}

2. 解析JSON并提取字段

接下来用Gson解析你的JSON字符串,然后遍历提取需要的字段:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Main {
    public static void main(String[] args) {
        String jsonFile = "{\n" +
                "  \"waypoints\": [\n" +
                "    {\n" +
                "      \"waypoint_index\": 0,\n" +
                "      \"trips_index\": 0,\n" +
                "      \"hint\": \"u_FYj4uKI=\",\n" +
                "      \"name\": \"\",\n" +
                "      \"location\": [28.068655, 41.180774]\n" +
                "    },\n" +
                "    {\n" +
                "      \"waypoint_index\": 4,\n" +
                "      \"trips_index\": 0,\n" +
                "      \"hint\": \"KiKhg4uKI=\",\n" +
                "      \"name\": \"\",\n" +
                "      \"location\": [20.75179, 29.031869]\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        Gson gson = new GsonBuilder().create();
        ResultOsrm resultOsrm = gson.fromJson(jsonFile, ResultOsrm.class);

        // 遍历提取目标字段
        for (Waypoint waypoint : resultOsrm.waypoints) {
            System.out.println("waypoint_index: " + waypoint.waypoint_index);
            System.out.println("location: " + waypoint.location.get(0) + ", " + waypoint.location.get(1));
            System.out.println("---");
        }
    }
}

3. 关键说明

  • Gson会自动匹配Java字段名和JSON键名(大小写敏感,所以要保证字段名完全一致),如果需要映射不同的名称,可以用@SerializedName注解,比如@SerializedName("waypoint_index") private int index;。
  • 对于JSON中的数组,Java可以用List或者数组类型(比如double[] location)来接收,根据你的需求选择即可。
  • 如果需要把Java对象转回JSON,直接调用gson.toJson(resultOsrm)即可,Gson只会序列化你定义的字段。

内容的提问来源于stack exchange,提问作者Talha K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:18:45