[英]Gson attribute name for collection
I have this Entity 我有这个实体
class Foo
{
public String FooName;
public String FooId;
}
I get an array of Foo
from a method and I serialize it to json string like this 我从方法中获取了一个
Foo
数组,并将其序列化为json字符串
Foo[] foos = getFoos();
String json = gson.toJson(foos, Foo[].class);
This generates 这会产生
[
{
"FooName" : "FirstFoo",
"FooId" : "1"
},
{
"FooName" : "SecondFoo",
"FooId" : "2"
}
]
which is fine except I have a requirement to have a wrapper attribute like this 这很好,除了我需要有这样的包装器属性
{
"foos":[
{
"FooName" : "FirstFoo",
"FooId" : "1"
},
{
"FooName" : "SecondFoo",
"FooId" : "2"
}
]
}
I know I can create a wrapper class 我知道我可以创建一个包装类
class Foos
{
Foo[] foos;
}
and use Foos.class with gson but I have 100s of classes like Foo
and I would hate to create a wrapper class for each. 并使用带有gson的Foos.class但是我有100个像
Foo
这样的类,我不想为每个类创建一个包装类。 I was also thinking about just doing some string manipulation to the original json returned to add the wrapper attribut but I'm keeping that for plan B (or even C). 我还在考虑对原来的json做一些字符串操作,返回添加包装器attribut,但我保留了计划B(甚至是C)。 So, I was wondering if there is a way in gson to add a wrapper attribute like what I'm asking above.
所以,我想知道在gson中是否有办法添加一个包装器属性,就像我上面提到的那样。
Thanks. 谢谢。
Heres a manual way to do this: 这是一种手动方式:
final Gson gson = new Gson();
final Foo[] foos = new Foo[] {};
final JsonElement elem = gson.toJsonTree(foos);
final JsonObject jsonObj = new JsonObject();
jsonObj.add("foo", elem);
System.out.println(jsonObj.toString());
JsonObject obj = new JsonObject();
obj.add("foos", gson.toJsonTree(foos, Foo[].class));
String json = obj.toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.