简体   繁体   English

Gson:如果序列化/反序列化目标是Object,是否可以保留类型信息

[英]Gson : Is there a way to preserve type information if serialization/deserialization target 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());
    }
}

The output is 输出是

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

I wish Gson can preserve type information, when it perform serialization/deserialization on Object type. 我希望Gson在对Object类型执行序列化/反序列化时可以保留类型信息。 Is there any elegant way to achieve so? 有没有达到此目的的优雅方法? Or, it is not possible? 还是不可能?

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

JSON only has one numeric type; JSON只有一种数值类型; it copies the Number type from JavaScript and this type has identical values to the Java Double type. 它从JavaScript复制Number类型,并且此类型的值与Java Double类型的值相同。

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. 您将必须通过为value变量使用更特定的类型或某种其他形式的显式类型匹配,来向Gson解析器提供更显式的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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