Gson : Is there a way to preserve type information if serialization/deserialization target is an Object

为君一笑 提交于 2019-12-25 05:32:40

问题


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());
    }
}

The output is

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

I wish Gson can preserve type information, when it perform serialization/deserialization on Object type. Is there any elegant way to achieve so? Or, it is not possible?


回答1:


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");



回答2:


JSON only has one numeric type; it copies the Number type from JavaScript and this type has identical values to the Java Double type.

You will have to provide more explicit information to the Gson parser either by using a more specific type for the value variable or some other form of explicit type matching.



来源:https://stackoverflow.com/questions/19523728/gson-is-there-a-way-to-preserve-type-information-if-serialization-deserializat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!