Gson serialize POJO with root value included?

送分小仙女□ 提交于 2019-12-30 01:40:07

问题


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!


回答1:


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



回答2:


Instead of hardcoding the type you can do:

...
jo.add(Foo.getClass().getSimpleName(), je);



回答3:


A better way to do this is to create a wrapper class and then create an object of Foo inside it.

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:

new GsonBuilder().create().toJson(responseWrapperObj);

which will give you the desired structure:

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



回答4:


If you are using Jackson api use the below lines

mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);



来源:https://stackoverflow.com/questions/4623329/gson-serialize-pojo-with-root-value-included

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!