【发布时间】: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 而不会失败。
【问题讨论】: