GSON的JSON数组引发错误“预期BEGIN_OBJECT但是STRING”

时间:2014-06-11 16:06:03

标签: java json gson

我正在尝试将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的新手,在理解它是如何工作方面遇到了问题。谁能帮助我理解我做错了什么?

1 个答案:

答案 0 :(得分:3)

你期待这个

    "keypoint": "2.1"

要映射到

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

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

使用Gson编写并注册您自己的TypeAdapter将执行此转换或将您的JSON更改为

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