Reputation: 2568
I have a java object with id,text,body,title
as class members with appropriate getters and setters and use Gson to convert POJO to json
Gson gson = new Gson();
String json = gson.toJson(object);
This returns a follwoing josn String
{
"id" : 1,
"text" : "Some text",
"body" : "Some text.",
"title" : "Some title."
}
How do i get the above json wrapped as following
"i1":{
"i2":{
"id" : 1,
"text" : "Some text",
"body" : "Some text.",
"title" : "Some title."
}
}
}
Right now the toString()
method is just empty. Should that be modified or should i1 and i2 be class members too?
Upvotes: 1
Views: 864
Reputation: 3856
You can wrap object with JsonObjects before turning into a json string. Something like this:
JsonObject i1 = new JsonObject();
JsonObject i0 = new JsonObject();
i1.add("i2", gson.toJsonTree(object));
i0.add("i1", i1);
String results = gson.toJson(i0);
System.out.println("results=" + results);
Upvotes: 3