我正在尝试解析这个JSON:
{
"Aatrox": {
"version": "5.2.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Ahri": {
"version": "5.2.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "the Nine-Tailed Fox"
},
"Akali": {
"version": "5.2.1",
"id": "Akali",
"key": "84",
"name": "Akali",
"title": "the Fist of Shadow"
},
....
}
正如您所看到的那些元素都具有相同的属性,所以我想将它们解析为元素列表,这里是我正在使用的类:
public class CampeonBO {
private String version;
private String id;
private String key;
private String name;
private String title;
//Getters and Setters
}
这就是我试图用Gson解析它的方式
Type type = new TypeToken<List<CampeonBO>>(){}.getType();
List<CampeonBO> campeones = gson.fromJson(bufferedReader, type);
我收到了错误:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
这显然是因为我的JSON中没有数组,我有3个属性“Aatrox,Ahri,Akali”,但它们都具有相同的属性,所以如何使用Gson将它们解析为列表?
答案 0 :(得分:4)
你告诉Gson将数据解析为List
,这意味着Gson希望解析一个JSON数组:
但是,您尝试解析的JSON实际上是一个JSON对象:
通常,解析JSON对象的Gson方法是将其解析为专用Java类型,就像使用CampeonBO
一样。但是,JSON对象在概念上也是一个映射,因此如果您尝试使用任意键解析JSON对象并且所有值都使用相同类型,则可以使用Map
作为解析Type
。
获得Map
后,您可以致电Map.values()
获取Collection
地图的值(如果需要,可以将其放入List
)
有关示例,请参阅How can I convert JSON to a HashMap using Gson?。
来自http://json.org/的图片。
答案 1 :(得分:0)
这是一个JSON,
{
"Aatrox": {
"version": "5.2.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Akali": {
"version": "5.2.1",
"id": "Akali",
"key": "84",
"name": "Akali",
"title": "the Fist of Shadow"
}
}
数组将是:
[
{
"version": "5.2.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade"
},
{
"version": "5.2.1",
"id": "Akali",
"key": "84",
"name": "Akali",
"title": "the Fist of Shadow"
}
]
请注意方括号。如果可能,请修改您的服务