curious1
curious1

Reputation: 14717

How to add an object as a property of a JsonObject object?

Here is what I am doing:

JsonObject jobj = new JsonObject();
jobj.addProperty("name", "great car");

I am hoping to add another property whose value is an object as follows:

jobj.addProperty("car", A_CAR_OBJECT);

But it appears that GSON does not allow me to do jobj.addProperty("car", A_CAR_OBJECT). I am going to eventually do the following:

String json = new Gson().toJson(jobj);

to get the Json string.

Is this doable? Am I using GSON the right way? Or should I just use a HashMap to throw all data into it and then new Gson().toJson()?

Upvotes: 19

Views: 32255

Answers (1)

Simon Arsenault
Simon Arsenault

Reputation: 1261

You could do it this way:

jobj.add("car", new Gson().toJsonTree(A_CAR_OBJECT));

Upvotes: 41

Related Questions