我有一个与此类似的 JSON,我通过发送 HTTP 请求来获取它。
{
"0": {
"name": "Chunk",
"type": "magic",
"item": "Chestplate",
"item_min_lvl": "70",
"id": {
"health": "0.3",
"spell": "24%",
"life": "0.1",
"xp": "24%",
"loot": "22%"
},
"def": "67"
},
"1": {
"name": "Thor",
"type": "normal",
"item": "Shoe",
"item_min_lvl": "12",
"id": {
"xp": "24%"
},
"def": "12"
},
"2": {
"name": "Clipper",
"type": "normal",
"item": "Sword",
"item_min_lvl": "51",
"id": {
"health": "1",
"life": "0.12",
"xp": "4%"
},
"min_dam": "11",
"max_dam": "7"
}
}
这是我的代码:
java.lang.reflect.Type type = new TypeToken<ArrayList<Map<String, Object>>>(){}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(json, type);//Error here
for(Map<String, Object> m : list)
{
//blah
}
它返回此错误预期为 BEGIN_ARRAY,但在第 1 行第 2 列为 BEGIN_OBJECT
谁能帮我解决这个错误吗?我是 JSON
和 GSON
的新手。请注意,某些“项目”不相同,因此我必须使用 TypeToken
。
最佳答案
您的 json 不包含数组(使用语法 []
),而是包含对象(使用语法 {}
)。
您可能需要使用new TypeToken<Map<String, <Map<String, Object>>>>(){}.getType();
关于Java-Gson 解析 "Expected BEGIN_ARRAY but was BEGIN_OBJECT",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25159186/