【问题标题】:How to parse dynamic JSON fields with GSON?如何使用 GSON 解析动态 JSON 字段?
【发布时间】:2011-08-13 09:47:23
【问题描述】:

所以我使用 GSON 来解析来自 API 的 JSON,并且一直不知道如何让它解析数据中的动态字段。

以下是查询返回的 JSON 数据示例:

{

-
30655845: {
    id: "30655845"
    name: "testdata
    description: ""
    latitude: "38"
    longitude: "-122"
    altitude: "0"
    thumbnailURL: http://someimage.com/url.jpg
    distance: 9566.6344386665
}
-
28688744: {
    id: "28688744"
    name: "testdata2"
    description: ""
    latitude: "38"
    longitude: "-122"
    altitude: "0"
    thumbnailURL: http://someimage.com/url.jpg
    distance: 9563.8328713012
}
}

我目前处理单个静态值的方式是使用一个类:

import com.google.gson.annotations.SerializedName;

public class Result 
{
@SerializedName("id")
public int id;

@SerializedName("name")
public String name;

@SerializedName("description")
public String description;

@SerializedName("latitude")
public Double latitude;

@SerializedName("longitude")
public Double longitude;

@SerializedName("altitude")
public Double altitude;

@SerializedName("thumbnailURL")
public String thumbnailURL;

@SerializedName("distance")
public Double distance;
}

然后我可以简单地使用 GSON 来解析它:

Gson gson = new Gson();

Reader reader = new InputStreamReader(source);

Result response= gson.fromJson(reader, Result.class);

我知道这适用于子数据,因为我可以查询并获取单个条目并非常容易地解析它,但是为数组中的每个值给出的随机整数值呢? (即 30655845 和 2868874)

有什么帮助吗?

【问题讨论】:

    标签: java json api gson


    【解决方案1】:

    根据GSON documentation,您可以执行以下操作:

    Type mapType = new TypeToken<Map<Integer, Result> >() {}.getType(); // define generic type
    Map<Integer, Result> result= gson.fromJson(new InputStreamReader(source), mapType);
    

    或者您可以尝试为您的班级写custom serializer

    免责声明:我也没有使用 GSon 的经验,但使用过其他框架,例如 Jackson。

    【讨论】:

    • 有什么方法可以解析相同但使用 NewtonSoft?
    猜你喜欢
    • 2011-11-30
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2020-04-22
    • 2015-11-14
    • 1970-01-01
    相关资源
    最近更新 更多