Ankur Khandelwal Ankur Khandelwal - 1 year ago 57
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 {
} catch (JSONException js) {

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.


This question is not duplicate.

@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 Source

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")));



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download