Need to preserve order of elements sent in JSON from Java
- by Kush
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.