Gson序列化包含根值的POJO? [英] Gson serialize POJO with root value included?

查看:141
本文介绍了Gson序列化包含根值的POJO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @XmlRootElement 
class Foo实现了Serializable {
私人诠释数字;
private String str;

public Foo(){
number = 10;
str =hello;


Gson会将这个序列化为一个JSON



{number:10,str:hello}



然而,我希望它是

{Foo:{number:10,str: hello}}



所以基本上包含顶层元素。我试图谷歌在Gson做到这一点,但没有运气。任何人都知道是否有办法做到这一点?



谢谢!

解决方案

您需要在对象树的顶部。像这样:

  Gson gson = new Gson(); 
JsonElement je = gson.toJsonTree(new Foo());
JsonObject jo = new JsonObject();
jo.add(Foo,je);
System.out.println(jo.toString());
//打印{Foo:{number:10,str:hello}}


I'm having a problem serializing an object using 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

{"number":10,"str":"hello"}.

However, I want it to be

{"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?

Thanks!

解决方案

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"}}

这篇关于Gson序列化包含根值的POJO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆