在Java中,如何在单个JSON对象中表示多个对象(相同类型)

时间:2011-06-20 16:00:57

标签: java javascript json

我需要将特定类型的属性传递给javascript,然后将其显示到网页

  @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需要读取ONE JSON对象,如下所示:

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

2 个答案:

答案 0 :(得分:2)

你正在做的是正确的方法。 JSON调用总是返回一个对象。

你得到的对象是一个数组,所以你可以像这样提取元素:

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

答案 1 :(得分:1)

使用json lib

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

JSONArray jsonArray = JSONArray.fromObject(mybeanList);

您也可以使用XStream执行此操作


另见