Unable to construct JSON response in this format
I need to construct JSON response in this format
{
label : "name",
items : [
{name : "Name1"},
{name : "Name2"}
]
}
Inside my Servlet program i used this way
List list = new ArrayList();
for (int i = 0; i <= 10; i++) {
list.add("Test");
}
JSONObject json = new JSONObject();
json.put("label", "name");
json.put("items", list.toArray());
开发者_Python百科 response.getWriter().write(json.toString());
With this format , When i checked Firebug , the response is coming this way :
{"label":"name","items":["Test","Test","Test","Test","Test","Test","Test","Test","Test","Test","Test"]}
Please tell me how to construct in this format .
You have to create the objects inside the Array. This should work:
List list = new ArrayList();
for (int i = 0; i <= 10; i++) {
JSONObject nextObject = new JSONObject();
nextObject.put("name", "Name" + i);
list.add(nextObject);
}
JSONObject json = new JSONObject();
json.put("label", "name");
json.put("items", list.toArray());
response.getWriter().write(json.toString());
One thing that i want say that in the json data you wanted is a data structure where we need to put json object to the list and then put the list to a json object referance. I think this link will help you.
精彩评论