java - 使用 GSON 序列化时包括对象类型

标签 java json gson

假设我有一些基本类型:

public class Base {
    String a = "a";
    Nested nested = new Nested()
}

public class Nested {
    String b = "b",
}

用 GSON 序列化它,我得到:

{
   "a": "a",
   "nested": {
      "b": "b"    
   }
}

一切都很好,但是如果我还想根据以下内容保留对象类型怎么办:

{
    "Base":
    {
       "a": "a",
       "nested": {
           "Nested": {
               "b": "b"  
           }  
       }
    }
}

我可以尝试编写一个自定义序列化程序来解决这个问题(假设也为 Nested 编写了一个等效序列化程序):

new JsonSerializer<Base>() {
    @Override
    public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
         Map<String, Base> selfMap = new HashMap<>();
         selfMap.put(src.getClass().getSimpleName(), src);
         return context.serialize(selfMap);
     }
}

然而,这个问题当然是在序列化基类型时我陷入了无限递归。

还有什么办法可以解决吗?

最佳答案

你可以这样试试

Base base = new Base();
base.a="a";  
base.b="b";

Gson gson = new Gson();
JsonElement je = gson.toJsonTree(base);
JsonObject jo = new JsonObject();
jo.add(Base.class.getName(), je);
System.out.println(jo.toString());

输出:

{"Base":{"a":"a","b":"b"}}

编辑:

供您在问题中修改。

你可以试试Genson

Base base = new Base();
base.a="a";
base.nested=new Nested();

Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
String json = genson.serialize(base);
System.out.println(json.replaceAll("\"@class\":",""));

输出:

{"Base","a":"a","nested":{"Nested","b":"b"}}

关于java - 使用 GSON 序列化时包括对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26118471/

相关文章:

java - Android - 广播接收器不记录消息

json - 如何在 VSCode 中创建每个工作区片段?

java - Json格式错误,已经获取数组时再请求数组

json - 如何在 Postman 等 REST 客户端上使用 Twilio

java - 如何以正确/列出的顺序获取 JSONObject 值?

java - 使用 GSON 序列化对象

java.lang.NoClassDefFoundError : com. google.gson.stream.JsonReader 在使用 Amazon S3 上传图像时在 android 中的 Pre-Lollipop 上出错

java - 获取线程java的运行时间

java - JComboBox 添加值

java - 将多行文本值设置为 imageview 不起作用