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
开发者_C百科 @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]
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";
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
- Google gson
精彩评论