简体   繁体   中英

Java Gson parse not deserializing correctly

I have a List<List<Integer>> with value

[[537316070],[306297332],[319303159],[538639811],[528406093],[166705854],[124574525],[967403337],[569514785],[304831454],[219384921],[308948513],[355538394],[297996417]]

after serializing it with Gson.

When I deserialize it using

List<List<Integer>> data = (List<List<Integer>>) GsonParser.gson.fromJson(datastr, List.class);

I am getting

[[5.3731607E8], [3.06297332E8], [3.19303159E8], [5.38639811E8], [5.28406093E8], [1.66705854E8], [1.24574525E8], [9.67403337E8], [5.69514785E8], [3.04831454E8], [2.19384921E8], [3.08948513E8], [3.55538394E8], [2.97996417E8]]

Does anyone know whats wrong?

Thanks

Gson , by default, parses any JSON number into a double . This happens in the ObjectTypeAdapter#read(JsonReader) method:

...
case NUMBER:
  return in.nextDouble();
...

Do the following

List<List<Integer>> data = GsonParser.gson.fromJson(json, new TypeToken<List<List<Integer>>>() {}.getType());

to get them as Integer instances.

The TypeToken is a Java hack to get the actual generic parameter types. The javadoc states

Constructs a new type literal. Derives represented class from type parameter.

Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM