java Gson 序列化包含根值的 POJO?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4623329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gson serialize POJO with root value included?
提问by fei
I'm having a problem serializing an object using Gson.
我在使用 Gson 序列化对象时遇到问题。
@XmlRootElement
class Foo implements Serializable {
private int number;
private String str;
public Foo() {
number = 10;
str = "hello";
}
}
Gson will serialize this into a JSON
Gson 会将其序列化为 JSON
{"number":10,"str":"hello"}
.
{"number":10,"str":"hello"}
.
However, I want it to be
但是,我希望它是
{"Foo":{"number":10,"str":"hello"}}
,
{"Foo":{"number":10,"str":"hello"}}
,
so basically including the top level element. I tried to google a way to do this in Gson, but no luck. Anyone knows if there is a way to achieve this?
所以基本上包括顶级元素。我试图在 Gson 中搜索一种方法来做到这一点,但没有运气。有谁知道是否有办法实现这一目标?
Thanks!
谢谢!
采纳答案by Nishant
You need to add the element at the top of the the object tree. Something like this:
您需要在对象树的顶部添加元素。像这样的东西:
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(new Foo());
JsonObject jo = new JsonObject();
jo.add("Foo", je);
System.out.println(jo.toString());
// Prints {"Foo":{"number":10,"str":"hello"}}
回答by jorgetown
Instead of hardcoding the type you can do:
您可以执行以下操作,而不是对类型进行硬编码:
...
jo.add(Foo.getClass().getSimpleName(), je);
回答by Krishnanunni P V
A better way to do this is to create a wrapper class and then create an object of Foo
inside it.
更好的方法是创建一个包装类,然后在其中创建一个对象Foo
。
Sample code:
示例代码:
public class ResponseWrapper {
@SerializedName("Foo")
private Foo foo;
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo= foo;
}
}
Then you can easily parse to JSON using:
然后您可以使用以下方法轻松解析为 JSON:
new GsonBuilder().create().toJson(responseWrapperObj);
which will give you the desired structure:
这将为您提供所需的结构:
{"Foo":{"number":10,"str":"hello"}}
回答by Ananth C
If you are using Hymanson api use the below lines
如果您使用的是 Hymanson api,请使用以下几行
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);