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()
?
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.
JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);
You could do it this way:
jobj.add("car", new Gson().toJsonTree(A_CAR_OBJECT));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With