Java-Gson 解析 "Expected BEGIN_ARRAY but was BEGIN_OBJECT"

标签 java gson

我有一个与此类似的 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

谁能帮我解决这个错误吗?我是 JSONGSON 的新手。请注意,某些“项目”不相同,因此我必须使用 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/

相关文章:

java - 实时抓取标记的 instagram 照片

Java Filenotfound 异常被抛出

java - 按照文件中定义的顺序获取所有 JSON 键

java - BlueJ 导入自定义类库

java.lang.ClassNotFoundException : org. 代码豪斯.jackson.map.JsonSerializableWithType

java - 尝试将 GSON 与自己的类一起使用时出错

java - 使用 GSON 反序列化两种不同的日期格式

java - 带有 Retrofit 2 的多个转换器

java - 带有 HTML 文件的 URLConnection.getContent

java - 使用谷歌 Gson 解析 Json Feed