Gson在序列化期间添加字段

jon*_*oun 28 java serialization gson

我找不到在Gson中序列化期间添加自定义字段的简单方法,我希望其他人可以提供帮助.

这是一个展示我的问题的示例类:

public class A {
  String id;
  String name;
  ...
}
Run Code Online (Sandbox Code Playgroud)

当我序列化类时,AI想要返回类似的东西:

{ "id":"123", "name":"John Doe", "url_to_user":"http://www.example.com/123" }
Run Code Online (Sandbox Code Playgroud)

其中url_to_user未存储在我的A类实例中,但可以使用A类实例中的数据生成.

有一个简单的方法吗?我宁愿避免编写整个序列化程序只是为了添加一个字段.

Jef*_*ica 54

Gson.toJsonTree得到JsonElement,用它可以动态交互.

A a = getYourAInstanceHere();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(a);
jsonElement.getAsJsonObject().addProperty("url_to_user", url);
return gson.toJson(jsonElement);
Run Code Online (Sandbox Code Playgroud)