Reputation: 10254
Hello all I am setting value to an object and then running gson.tojson(myObject)
This works fine and the output looks like:
{"val1":22,"val2":4,"val3":34,"val4":1046.0,"val5":"hello","val6":true}
However I now need my json string to look like
{"myJson": {"val1":22,"val2":4,"val3":34,"val4":1046.0,"val5":"hello","val6":true}}
is there a built in way to do this or should I just do sting concat?
Upvotes: 2
Views: 270
Reputation: 23319
Yes, you just need to get the JsonTree
and add an inner object to it
JsonElement innerObject = gson.toJsonTree(myObject);
JsonObject outerObject = new JsonObject();
outerObject.add("myJson",innerObject);
Now, outerObject
has innerObject
so you can take it from there, convert it to String
if you want.
String json = outerObject.toString();
Upvotes: 5
Reputation: 2614
You can create a wrapper class which has your object set in its property "myJson".
public class Wrapper {
<Yourclass> myJson;
public Wrapper(<Yourclass> obj){
myJson = obj;
}
}
Afterwards create the JSON based on the Wrapper.
Upvotes: 0
Reputation: 15050
I don't know if there is a option for that with Gson but you can create a wrapper class for your object :
class ObjectWrapper {
Object myJsonObject;
}
And use gson.toJson()
on the wrapped object.
Upvotes: 0