Gson serialize POJO with root value included?

前端 未结 4 1229
独厮守ぢ
独厮守ぢ 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:23

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

提交回复
热议问题