Gson serialize POJO with root value included?

前端 未结 4 1239
独厮守ぢ
独厮守ぢ 2020-12-29 22:52

I\'m having a problem serializing an object using Gson.

@XmlRootElement
class Foo implements Serializable {
    private int number;
    private String str;

         


        
4条回答
  •  清歌不尽
    2020-12-29 23:10

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

提交回复
热议问题