[{
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.
@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.
The status
is also a JSONObject
, yes
and no
are properties of this JSONObject
of type JSONArray
and the main object is in a 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")));
JSONArray array = new JSONArray(Collections.singletonList(object));
System.out.println(array);
Output:
[{"name":"Name","id":12345,"status":{"no":["n1","n2","n3"],"yes":["N1","n2","n3"]}}]
I hope before array there will be a JSONObject or may be some name for array: Try below code if this array comes in a JSONObject:
try {
JSONObject object=new JSONObject();
JSONArray jsonarray=object.getJSONArray();
if(jsonarray.length()>0)
{
for(int i=0; i<jsonarray.length();i++)
{
object.put("id",12345);
object.put("name",Name);
jsonarray.put("yes");
jsonarray.put("no);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
otherwise:
try {
JSONArray jsonarray=new JSONArray("Name of Array");
if(jsonarray.length()>0)
{
for(int i=0; i<jsonarray.length();i++)
{
object.put("id",12345);
object.put("name",Name);
jsonarray.put("yes");
jsonarray.put("no);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.