本文介绍了Gson在序列化过程中添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是一个示例类来显示我的问题:
public class A {
String id;
字符串名称;
...
}
当我序列化类AI想要返回时例如:
{id:123,name:John Doe,url_to_user: http://www.example.com/123}
其中url_to_user未存储在我的实例中的类A,但可以用类A的实例中的数据生成。
有没有简单的方法来做到这一点?我宁愿避免编写一个完整的序列化器来添加一个字段。
使用使用 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);
I can't find a simple way to add a custom field during serialization in Gson and I was hoping someone else may be able to help.
Here is a sample class to show my issue:
public class A {
String id;
String name;
...
}
When I serialize class A I would like to return something like:
{ "id":"123", "name":"John Doe", "url_to_user":"http://www.example.com/123" }
where url_to_user is not stored in my instance of class A, but can be generated with data in the instance of class A.
Is there a simple way of doing this? I would prefer to avoid writing an entire serializer just to add one field.
解决方案 Use Gson.toJsonTree
to get a JsonElement
, with which you can interact dynamically.
A a = getYourAInstanceHere();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(a);
jsonElement.getAsJsonObject().addProperty("url_to_user", url);
return gson.toJson(jsonElement);
这篇关于Gson在序列化过程中添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!