开发者

How do I put more than one JSON instance in a single JSON object using net.sf.json.JSONObject library

开发者 https://www.devze.com 2023-03-14 07:27 出处:网络
//create the JSON Object to pass to the client JSONObject object=new JSONObject(); //one instance object.put(\"name\",\"somethi开发者_StackOverflow中文版ng2\");
 //create the JSON Object to pass to the client
 JSONObject object=new JSONObject();

 //one instance
 object.put("name","somethi开发者_StackOverflow中文版ng2");
 object.put("status", "up");

 //second instance
 object.put("name", "something2");
 object.put("status", "down");

 String json = object.toString();  

 response.getOutputStream().print(json);

 System.out.println("JSON Contents: "+json);

Desired output: {name: something1, status: up}, {name: something2, status: down}... etc


You need to have JSONArray :

JSONArray jsonarray = new JSONArray(); jsonarray.add(object)...


Instead of {name: something1, status: up}, {name: something2, status: down}, which is not valid JSON, I recommend targeting an array structure, such as [{name: something1, status: up}, {name: something2, status: down}]. So, you'd build this with net.sf.json.JSONArray, adding JSONObjects, built similarly to what you've already got. Of course, you'd need to change it to make two different JSONObjects, each of which would have the elements "name" and "status" added only once each.


In this case you'd have to use JSONArray instead.

List<Map> list = new ArrayList<HashMap>();
Map map1 = new HashMap();  
map1.put("name","something");  
Map map2 = new HashMap();  
map2.put("status", "up"); 
list.add(map1);
list.add(map2);

JSONArray array = JSONArray.fromObject(list);  
String json = array.toString();  
System.out.println("JSON: "+ json);
0

精彩评论

暂无评论...
验证码 换一张
取 消