0
@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;
  }
5
  • 1
    Why don't you sort your Java objects before you put them in a JSON array? And I think your loop should be for (Stuff i : stuff) Commented Dec 7, 2011 at 3:33
  • JSONObjects are not comparable. So, sort by what? Commented Dec 7, 2011 at 3:36
  • @James, he can sort by whatever he wants. He can sort his Collection<Stuff> before he iterates over it. He can break apart each Stuff into a TreeMap where key=getId() and val=getName(), for example, then iterate over the TreeMap and build his JSON array. He could extend the JSONObject class and make it comparable. Commented Dec 7, 2011 at 3:41
  • @Paul, I agree. I'm just trying to get him/her to provide more information, so we don't have to list all those possibilities. Commented Dec 7, 2011 at 4:53
  • @JamesClark, oops, sorry, I thought you were asking me (even though you didn't reference me). Didn't mean to jump in on your quiz! :) Commented Dec 7, 2011 at 4:57

1 Answer 1

3

For net.sf.json library:

Object[] myArray = jArray.toArray();
myArray = Arrays.sort(myArray);
JSONArray sortedJArray = new JSONArray();
for (Object obj : myArray) {
  sortedJArray.add(obj);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Json-lib (the library you mentioned) makes it easy to work with collections and arrays (examples): JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );

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.