Need to preserve order of elements sent in JSON from Java

Posted by Kush on Stack Overflow See other posts from Stack Overflow or by Kush
Published on 2012-04-07T17:26:41Z Indexed on 2012/04/07 17:28 UTC
Read the original article Hit count: 448

Filed under:
|
|
|

I'm using JSON.org APIs for Java to use JSON in my JSP webapp, I know JSONObject doesn't preserve order of elements the way they are put into it and one has to use JSONArray for that but I don't know how to use it since I need to send key and value both as received from the database, and here I'm sending data to jQuery via JSON where I need the order of data to be maintained.

Following is my servlet code, where I'm getting results from the database using ORDER BY and hence I want the order to be exact as returned from the database. Also this JSON object requested using $.post method of jQuery and is used to populate dropdown on reciever page.

ResultSet rs = st.executeQuery("SELECT * FROM tbl_state order by state_name");
JSONObject options = new JSONObject();
while(rs.next())
    options.put(rs.getString("state_id"),rs.getString("state_name"));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(options);

Thanks.

© Stack Overflow or respective owner

Related posts about JSON

Related posts about jsp