问题
I have the following exception while deserializing an JSON to object using Gson:
com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@588722d6 failed to deserialized json object [{"time":1378911600000,"total":0},{"time":1378912500000,"total":0},{"time":1378913400000,"total":2,"sum":130000,"avgLen":65000.0}] given the type com.google.gson.ParameterizedTypeImpl@490ca2fa
The class which should represent the JSON is:
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;
}
}
the deserialized code is:
String json = "{\"avgEngLength\":[{\"time\":1378905300000,\"total\":0},{\"time\":1378906200000,\"total\":2,\"sum\":130000,\"avgLen\":65000.0}]}";
Gson gson = new GsonBuilder().create();
return gson.fromJson(json, Api.class);
The odd thing is that it works on some machines and not on others. Any idea?
回答1:
I tried your example with this:
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);
}
and it worked (pay attention that your string in example has no escaped quotes).
Api [avgEngLength=[ApiData [time=1378905300000, total=0, sum=null, avgLen=null], ApiData [time=1378906200000, total=2, sum=130000, avgLen=65000.0]]]
So my best guess it that your team is working with different versions of the library. I'm using Gson 2.2.4 and I checked the source code: that error string is not present in the library.
来源:https://stackoverflow.com/questions/18756130/failed-to-deserialize-an-object-with-list-using-gson