问题
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()
?
回答1:
You could do it this way:
jobj.add("car", new Gson().toJsonTree(A_CAR_OBJECT));
来源:https://stackoverflow.com/questions/22585970/how-to-add-an-object-as-a-property-of-a-jsonobject-object