stackoverflow
stackoverflow

Reputation: 19454

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

 //create the JSON Object to pass to the client
 JSONObject object=new JSONObject();

 //one instance
 object.put("name","something2");
 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

Upvotes: 2

Views: 2719

Answers (3)

Benjamin Muschko
Benjamin Muschko

Reputation: 33436

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

Upvotes: 0

Programmer Bruce
Programmer Bruce

Reputation: 66943

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.

Upvotes: 0

Sergei Chicherin
Sergei Chicherin

Reputation: 2050

You need to have JSONArray :

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

Upvotes: 2

Related Questions