2
 //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

3 Answers 3

2

You need to have JSONArray :

JSONArray jsonarray = new JSONArray(); jsonarray.add(object)...
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.