Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

gson

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()?

like image 687
curious1 Avatar asked Mar 23 '14 01:03

curious1


People also ask

How do I add values to a JSON object in Java?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

How do I add a list to a JSON object in Java?

JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);


1 Answers

You could do it this way:

jobj.add("car", new Gson().toJsonTree(A_CAR_OBJECT));
like image 62
Simon Arsenault Avatar answered Oct 06 '22 07:10

Simon Arsenault