简体   繁体   中英

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. 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; 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.

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