Gson: Is there a way to store type information if the goal of serialization / deserialization is an object

I have the following code

import com.google.gson.Gson; /** * * @author yccheok */ public class JavaApplication18 { public static class Holder { public Object value; } /** * @param args the command line arguments */ public static void main(String[] args) { Gson gson = new Gson(); Integer i = new Integer(123); Holder holder = new Holder(); holder.value = i; String json = gson.toJson(holder); System.out.println(json); Holder newHolder = gson.fromJson(json, Holder.class); System.out.println(newHolder.value.getClass()); } } 

Output signal

 {"value":123} class java.lang.Double 

I want Gson to save type information when it serializes / deserializes by type of object. Is there any elegant way to achieve this? Or is it impossible?

0
source share
2 answers

Try this way

  JsonObject element = gson.fromJson (json, JsonObject.class); if(element.get("value") instanceof JsonPrimitive ) System.out.println("true"); else System.out.println("false"); 
0
source

JSON has only one digital type; it copies the Number type from JavaScript, and this type has identical values ​​for the Java Double type.

You will need to provide more explicit information for the Gson parser, either using a more specific type for the value variable, or using another form of explicit type matching.

0
source

Source: https://habr.com/ru/post/1246741/


All Articles