问题
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