Sahin Yanlık
Sahin Yanlık

Reputation: 1201

Json Object Item Order

I have written some code;

JSONArray ja = new JSONArray();
     try {
        ResultSetMetaData metaData = rslt.getMetaData();
        while ( rslt.next() ){
            JSONObject jo = new JSONObject();
            LinkedHashMap<String, String> jsonOrderedMap = new LinkedHashMap<String, String>();

            for(int i = 0 ; i < metaData.getColumnCount(); i++){
                jsonOrderedMap.put(metaData.getColumnName(i+1), rslt.getString(i+1) );
            }
            System.out.println(jsonOrderedMap);
            /* This doesn't work */
            ja.put(jsonOrderedMap);
            //System.out.println(ja);

        }
     } catch (Exception e) {
    }

I'am tring to order my json object ( I know it is not supposed to ordered , but I need it) It works until when I try to put my jsonOrderedMap to json array. Before JsonArray, json object looks like this :

{CUSTOMER_SECTOR_ID=611, CUSTOMER_NO=0013114193, CUSTOMER_NAME=asdfasdfds}

After putting some jsonOrderedMap to jsonArray, It looks like this;

[{"CUSTOMER_NAME":"qweqwe","CUSTOMER_NO":"0000003124","CUSTOMER_SECTOR_ID":"611"},
 {"CUSTOMER_NAME":"MAD.","CUSTOMER_NO":"0000003133","CUSTOMER_SECTOR_ID":"611"}]

As you can see it is not same order. Do you have any idea to fix it ? I am using gson library.

Upvotes: 1

Views: 881

Answers (2)

Ilya
Ilya

Reputation: 29703

Jackson JSON Processor saves order. Simple example of usage:

   static ObjectMapper o = new ObjectMapper();
   public static void main(String[] args) throws IOException 
   {
      List<Map> array = new ArrayList<Map>();
      Map<String, String> obj1 = new LinkedHashMap<String, String>();
      obj1.put("CUSTOMER_SECTOR_ID", "Id");
      obj1.put("CUSTOMER_NO", "No");
      obj1.put("CUSTOMER_NAME", "Name");
      array.add(obj1);
      System.out.println(o.writeValueAsString(array));
   }

Maven dependency

  <dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-mapper-asl</artifactId>
     <version>1.8.5</version>
  </dependency>

Upvotes: 0

Joffrey
Joffrey

Reputation: 37829

Fields in a JSON objects don't have any order, because they are supposed to be accessed by their name (key).

If you need to keep an order, you have to use a JSON array instead.

I can't see why you would need named fields to be ordered, but if you really need to do so, you can use an array containing the fields of your JSON object.

This post describes how to do so (thanks @SergioMartinez for the link, it saved me so much time!).

Upvotes: 2

Related Questions