Ankur Khandelwal Ankur Khandelwal - 2 months ago 6
Android Question

I need to create json object in java. How will I do it?

[{
id: 12345, //Id given by android app
name: Name,
status: {
yes: [N1, n2, n3],
no: [n1, n2 ,n3]
}
}]


How will I write json object for this in java?

My Attempt:

JSONObject object=new JSONObject();
JSONArray jsonarray=new JSONArray();
try {
object.put("id",12345);
object.put("name",Name);
jsonarray.put("yes");
jsonarray.put("no");
} catch (JSONException js) {
js.printStackTrace();
}


I think the problem is with jsonarray. I need to write again the jsonarray object. But I am not able to figure out how will I do it.

Edit

This question is not duplicate.
Justify

@ShaishavJogani I don't think this question is a duplicate of the question you provided a link to because this question is about generating JSON and this is about parsing JSON. – Андрей Беньковский

Answer

The status is also a JSONObject and yes and no are properties of this JSONObject of type JSONArray, so I would do it rather like this:

JSONObject object = new JSONObject();
object.put("id", 12345);
object.put("name", "Name");
JSONObject status = new JSONObject();
object.put("status", status);
status.put("yes", new JSONArray(Arrays.asList("N1", "n2", "n3")));
status.put("no", new JSONArray(Arrays.asList("n1", "n2", "n3")));

System.out.println(object);

Output:

{"name":"Name","id":12345,"status":{"no":["n1","n2","n3"],"yes":["N1","n2","n3"]}}
Comments