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

That's what I'm doing:

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

I hope to add another property whose value is the following object:

 jobj.addProperty("car", A_CAR_OBJECT); 

But it looks like GSON is not letting me do jobj.addProperty("car", A_CAR_OBJECT) . I will eventually do the following:

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

to get the json string.

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

+8
java json gson
source share
1 answer

You can do it as follows:

 jobj.add("car", new Gson().toJsonTree(A_CAR_OBJECT)); 
+21
source share

All Articles