GSON自定义分析 [英] GSON Custom parsing
问题描述
您好我正在写与输出JSON格式信息的外部Web服务接口的Android应用程序。
Hi I'm writing an android App that interfaces with an external webservice that outputs JSON formatted info.
我使用GSON生成Web服务输出的POJO,但我有这个实体的问题:
I'm using GSON to generate POJOs for the output of the web service, but I'm having a problem with this entity:
player: {
1: {
number: "6",
name: "Joleon Lescott",
pos: "D",
id: "2873"
},
2: {
number: "11",
name: "Chris Brunt",
pos: "D",
id: "15512"
},
3: {
number: "23",
name: "Gareth McAuley",
pos: "D",
id: "15703"
}
}
使用如 http://www.jsonschema2pojo.org/ 服务,我能够产生一个POJO符合这个输出是这样的:
Using a service like http://www.jsonschema2pojo.org/ I was able to generate a POJO that matches to this output like this:
public class Player {
@SerializedName("1")
@Expose
private com.example._1 _1;
@SerializedName("2")
@Expose
private com.example._2 _2;
.....
}
public class _1 {
@Expose
private String name;
@Expose
private String minute;
@Expose
private String owngoal;
@Expose
private String penalty;
@Expose
private String id;
....
}
不过,我想这个调整一点点,而不是具有_1的对象,_2,等等,我想有一个包含所有数据的数组或列表,像这样:
However I would like to tweak this a little bit and instead of having an object for _1, _2, etc, I would like to have an array or list containing all data, like this:
public class Players{
private List<Player> players;
}
public class Player{
@Expose
private int position;
@Expose
private String name;
@Expose
private String minute;
@Expose
private String owngoal;
@Expose
private String penalty;
@Expose
private String id;
....
}
我怎么能做到这一点,无需手动解析JSON文件?
How can I accomplish this, without manually parsing the JSON file?
推荐答案
注册一个 TypeAdapter
您播放
类。在反序列化
方法遍历键在 JSON
,并将它们添加到的ArrayList
。这应该工作,我想。在伪code的例子:
Register a TypeAdapter
for your Players
class. In the deserialize
method iterate over keys in the json
and add them to an ArrayList
. That should work, I think. An example in pseudo-code:
class PlayersAdapter implements JsonDeserializer<Players> {
public Players deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
List<Player> players = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
players.add(ctx.deserialize(entry.getValue(), Players.class));
}
return new Players(players);
}
}
// ...
Gson gson = new GsonBuilder()
.registerTypeAdapter(Players.class, new PlayersAdapter())
.create();
这篇关于GSON自定义分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!