如何解析与GSON动态JSON领域? [英] How to parse dynamic JSON fields with GSON?
问题描述
所以我使用GSON从一个API解析JSON和我坚持就如何把它解析动态字段中的数据。
So I'm using GSON to parse JSON from an API and am stuck as to how to have it parse the dynamic fields in the data.
下面是查询返回的JSON数据的一个例子:
Here is an example of the JSON data returned on a query:
{
-
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
}
}
我目前正在处理一个静态值的方法是使用一个类:
The way I am currently handling the single static values is with a class:
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解析是:
And then I can simply use GSON to parse that:
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
Result response= gson.fromJson(reader, Result.class);
我知道这个工程的子数据,我可以查询和获取单个条目,并解析很容易,但对于数组中的每个值给出的随机整数? (即30655845和2868874)
I know this works on the sub-data as I can query and get a single entry and parse that quite easily, but what about the random integer values given for each value in the array? (ie the 30655845 and 2868874)
任何帮助吗?
推荐答案
据的 GSON文档你可以做这样的事情:
According to GSON documentation you can do things like:
Type mapType = new TypeToken<Map<Integer, Result> >() {}.getType(); // define generic type
Map<Integer, Result> result= gson.fromJson(new InputStreamReader(source), mapType);
或者你可以尝试写<一个href=\"http://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserializ\">custom串行为你的类。
免责声明:我也有GSON但像杰克逊其他框架没有经验
Disclaimer: I too, have no experience with GSon but with other frameworks like Jackson.
这篇关于如何解析与GSON动态JSON领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!