【问题标题】:GSON : java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAYGSON:java.lang.IllegalStateException:应为 BEGIN_OBJECT 但为 BEGIN_ARRAY
【发布时间】:2014-04-24 16:59:50
【问题描述】:

我正在尝试使用 gson 解析下面的 json 字符串,我收到了这个异常。

[{"target":"target 1","datapoints":[[12345678, null],[3456123,null],[908976712,12345677.0],[67543678, 4567.0]]}, {"target":"target 2","datapoints":[[12345678, 50215.0],[345645123,null],[908976712,null],[67543678, 4567.0]]}]

这是我的模型类: 指标

public class Metric implements Serializable{
String target;
Datapoint[] datapoints;

//setters and getters
}

数据点

public class Datapoint implements Serializable{
long time;
long count;
//setters and getters
}

这就是我尝试使用 gson 解析 json 的方式

Gson gson = new GsonBuilder().create();
 JsonArray array = jsonParser.parse(jsonString).getAsJsonArray();
 for (JsonElement element : array) {
      Metric metric = gson.fromJson(element, Metric.class);
      //do something with the metric object. probably read all the datapoints and display
 }

这是抛出的异常

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

异常很明显,它需要一个对象(可能是数据点),但它遇到了一个数组。我确信我的模型类是导致问题的原因,但我不明白我的模型类应该是什么样子才能解析该 json 而不会失败。

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    您的 datapoints 元素不是 JSON 对象,它们是 JSON 数组,看似由 JSON 数字和 JSON 空值组成。

    [
        12345678,
        null
    ],
    

    您将无法(默认情况下)将其映射到Datapoint POJO。您可以改为使用

    Integer[][] datapoints; 
    

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 2016-12-27
      • 2013-08-10
      • 2017-10-16
      • 1970-01-01
      • 2013-05-15
      • 2017-08-04
      • 2021-05-27
      相关资源
      最近更新 更多