stackoverflow
stackoverflow

Reputation: 19474

In Java, How do I represent multiple objects (of same type) in a single JSON object

I need to pass the attribtutes of particular type, as apart of a restful service to a javascript which will then display them to a webpage

  @GET
  @Produces("application/json")
  @Consumes("application/json") 
  @Path("/getStatusAll")

  public void getStatusAll(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response) throws ServletException,
      IOException

{

 JSONArray jArray = new JSONArray();

 Collection<S> s = Manager.getS().values();
 for (Server i : svr)
 {
   JSONObject m = new JSONObject();

   m.put("name",i.getName());
   m.put("status",i.getStatus());

   jArray.add(m);

 }

 return jArray.toString();


    response.getOutputStream().print(jArray);
     response.flushBuffer();
}

JAVASCRIPT will need to read ONE JSON object looking like:

[ {name:someName0, status: someStatus},
 {name:someName1, status: someStatus},
 {name:someName2, status: someStatus}...etc]

Upvotes: 0

Views: 647

Answers (2)

MBCook
MBCook

Reputation: 14514

What you're doing is the correct way to do it. JSON calls always return one object.

The object you got back is an array, so you can extract the elements like this:

var myResponse = makeJSONCall();

// You have received myResponse.length objects, you can bind them
// to variables if you want

var thingOne = myResponse[0];
var thingTwo = myResponse[1];
...

// You can use them from their variable names or straight from the array

thingOne.name = "Joe Bob";
myResponse[3].status = "Tired";

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240948

using json lib

List mybeanList = new ArrayList();
mybeanList.add(myBean1);
mybeanList.add(myBean2);

JSONArray jsonArray = JSONArray.fromObject(mybeanList);

You can also use XStream to do this


See Also

Upvotes: 1

Related Questions