stackoverflow
stackoverflow

Reputation: 19454

How do I sort JSONObjects in an JSONArray in Java (Server side)?

@GET
  @Produces("application/json")
  @Consumes("application/json")
  @Path("/getStuff/{id}")
  public String getStuff(
      @PathParam("id") String id,
      @Context HttpServletRequest request,
      @Context HttpServletResponse response) throws Exception
  {
      Collection<Stuff> stuff = Manager.getStuff().values();
      JSONArray jArray = new JSONArray();    
      for (Stuff i : stuff)
      {          
        jsnObjct.put("id", i.getId());
        jsnObjct.put("name", i.getName());
        jArray.add(jsnObjct);
      }
      json = jArray.toString();
      response.setContentType("text/javascript");
      response.getOutputStream().print(json);
      response.flushBuffer();  
      return null;
  }

Upvotes: 0

Views: 8056

Answers (1)

Shaun
Shaun

Reputation: 2476

For net.sf.json library:

Object[] myArray = jArray.toArray();
myArray = Arrays.sort(myArray);
JSONArray sortedJArray = new JSONArray();
for (Object obj : myArray) {
  sortedJArray.add(obj);
}

Upvotes: 3

Related Questions