Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson serialize POJO with root value included?

Tags:

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!

like image 527
fei Avatar asked Jan 07 '11 07:01

fei


1 Answers

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"}} 
like image 186
Nishant Avatar answered Sep 28 '22 17:09

Nishant