小编典典

如何使用GSON解析动态JSON字段?

json

因此,我使用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)

有什么帮助吗?


阅读 334

收藏
2020-07-27

共1个答案

小编典典

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

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

或者,您可以尝试为您的类编写自定义序列化程序。

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

2020-07-27