问题描述
我有以下代码:
import com.google.gson.Gson;
$ b / **
*
* @author yccheok
* /
public class JavaApplication18 {
public static class Holder {
公共对象值;
}
/ **
* @param args命令行参数
* /
public static void main(String [] args){
Gson gson = new Gson();
整数i =新的整数(123);
持有人持有人=新持有人();
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());
$ / code $ / pre
$ b $ p输出是
{value:123}
class java.lang.Double
我希望Gson在对象类型上执行序列化/反序列化时可以保留类型信息。有没有优雅的方式来实现这一目标?或者,这是不可能的?
解决方案 JSON只有一种数字类型;它从JavaScript复制Number类型,并且此类型具有与Java Double类型相同的值。
您将不得不向Gson解析器提供更明确的信息,方法是使用值
变量或某种其他形式的显式类型匹配的更具体类型。
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?
解决方案 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.
这篇关于Gson:如果序列化/反序列化目标是一个对象,有没有办法保存类型信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!