首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用GSON解析动态JSON字段?

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

Stack Overflow用户
提问于 2011-04-27 05:57:09
回答 1查看 24K关注 0票数 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)

有什么帮助吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-28 03:45:10

根据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的经验,但对像杰克逊这样的其他框架没有经验。

票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5796948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档