Java 无法使用Gson反序列化具有列表的对象
在使用Gson将JSON反序列化到对象时,出现以下异常: com.google.gson.JsonParseException:JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@588722d6未能反序列化json对象[{“时间”:1378911600000,“总计”:0},{“时间”:1378912500000,“总计”:0},{“时间”:1378913400000,“总计”:2,“总和”:130000,“avgLen”:65000.0}]给定com.google.gson类型。ParameterizedTypeImpl@490ca2fa 应该表示JSON的类是:Java 无法使用Gson反序列化具有列表的对象,java,json,gson,Java,Json,Gson,在使用Gson将JSON反序列化到对象时,出现以下异常: com.google.gson.JsonParseException:JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@588722d6未能反序列化json对象[{“时间”:1378911600000,“总计”:0},{“时间”:1378912500000,“总计”:0},{“时间”:1378913400000,“总计”:2,“总和”:13
public class Api{
private List<ApiData> avgEngLength;
public Api() {
}
}
public class ApiData{
private Long time;
private Long total;
private Long sum;
private Double avgLen;
public ApiData(Long time, Long total, Long sum, Double avgLen) {
this.time = time;
this.total= total;
this.sum= sum;
this.avgLen= avgLen;
}
}
奇怪的是,它在某些机器上工作,而在其他机器上不工作。
有什么想法吗?我试过你的例子:
public static void main(String[] args) {
String s = "{\"avgEngLength\":[{\"time\":1378905300000,\"total\":0},{\"time\":1378906200000,\"total\":2,\"sum\":130000,\"avgLen\":65000.0}]}";
Gson gson = new GsonBuilder().create();
Api a = gson.fromJson(s, Api.class);
System.out.println(a);
}
而且它起作用了(请注意,示例中的字符串没有转义引号)
所以我猜你的团队正在使用不同版本的库。我使用的是Gson 2.2.4,我检查了源代码:该错误字符串在库中不存在。正如我所说,它在某些机器上工作(我认为仅在windows上),而在其他机器上不工作。您是否有时间在引发异常的计算机上检查库版本?您使用的是什么版本的Gson?您是否向构建器提供了一些示例中未报告的自定义行为?
public static void main(String[] args) {
String s = "{\"avgEngLength\":[{\"time\":1378905300000,\"total\":0},{\"time\":1378906200000,\"total\":2,\"sum\":130000,\"avgLen\":65000.0}]}";
Gson gson = new GsonBuilder().create();
Api a = gson.fromJson(s, Api.class);
System.out.println(a);
}
Api [avgEngLength=[ApiData [time=1378905300000, total=0, sum=null, avgLen=null], ApiData [time=1378906200000, total=2, sum=130000, avgLen=65000.0]]]