【问题标题】:JSON Array With GSON Throws Error "Expected BEGIN_OBJECT but was STRING"带有 GSON 的 JSON 数组引发错误“预期为 BEGIN_OBJECT 但为 STRING”
【发布时间】:2014-06-11 16:06:02
【问题描述】:

我正在尝试将 JSON 数组转换为 Java 对象,但在理解如何使用 GSON 时遇到问题。

JSON 数组如下所示:

"[
  {
    "category": "1",
    "checks": [
      {
        "check": "1.1",
        "penaltypoints": "1.1",
        "keypoint": "1.1"
      },
      {
        "check": "1.2",
        "penaltypoints": "1.2",
        "keypoint": "1.2"
      }
    ]
  },
  {
    "category": "2",
    "checks": [
      {
        "check": "2.1",
        "penaltypoints": "2.1",
        "keypoint": "2.1"
      },
      {
        "check": "2.2",
        "penaltypoints": "2.2",
        "keypoint": "2.2"
      }
    ]
  }
]"

我对应的Java类是:

class Category {
    public String description;
    public List<Check> checks;
}

class Check {
    public String description;
    public float penaltyPoints;
    public KeyPoint keypoint;
}

class KeyPoint {
    public String description;
}

这就是我对 GSON 的称呼:

Gson gson = new Gson();         
Category categoriesArray[] = gson.fromJson(jsonString, Category[].class);

目前它正在抛出以下错误:

Expected BEGIN_OBJECT but was STRING at line 1 column 125

我是 GSON 的新手,无法理解它的工作原理。谁能帮我理解我做错了什么?

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    你期待这个

        "keypoint": "2.1"
    

    映射到

    public KeyPoint keypoint;
    ...
    class KeyPoint {
        public String description;
    }
    

    在 Java-JSON 转换中,POJO 旨在映射到 JSON 对象,反之亦然。在这里,您尝试将 JSON String 映射到 POJO。默认情况下这不起作用。

    要么使用 Gson 编写并注册您自己的 TypeAdapter 来进行此转换,要么将您的 JSON 更改为

    "keypoint" : {
         "description" : "2.1"
    }
    

    【讨论】:

    • 谢谢,这似乎是问题所在。我在我的脑海里有不同的映射!当计时器允许我时,我会接受你的回答:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    相关资源
    最近更新 更多