21

I was trying to construct an JSON String using JSON Object

I want the JSON String to be constructed this way

{
    "Level": "3",
    "Name": "testLogger",
    "IPADDRESS": "testMachiene",
    "Message": "hiiiiiiiiii",
    "TimeStamp": "test12345678"
}

This is my simple program to do so

package com;

import org.json.JSONObject;

public class Teste {

    public static void main(String args[]) throws Exception {

        int loglevel = 3;
        String loggerName = "testLogger";
        String machieneName = "testMachiene";
        String timeStamp = "test12345678";
        String message = "hiiiiiiiiii";

        JSONObject obj = new JSONObject();

        obj.put("TimeStamp", message);
        obj.put("Message", timeStamp);
        obj.put("IPADDRESS", machieneName);
        obj.put("Name", loggerName);
        obj.put("Level", loglevel);

        System.out.println(obj.toString());

    }

}

And it was constructing this way

{
    "Name": "testLogger",
    "TimeStamp": "hiiiiiiiiii",
    "Message": "test12345678",
    "Level": 3,
    "IPADDRESS": "testMachiene"
}

My question is that why its changing the order of attributes

Can i have the order in which i wish ??

Pawan
  • 31,545
  • 102
  • 256
  • 434
  • 2
    Why would the order matter here? It is a Map not a list. You anyway will use a key to access the elements and not an index. – mohkhan Jun 21 '13 at 07:01
  • The short answer is "No, you can't"! – Stephen C Jun 21 '13 at 07:05
  • Well, they state the following here (if this is indeed gson). http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/JsonObject.html "The member elements of this object are maintained in order they were added." – Ted Aug 05 '14 at 14:47

3 Answers3

41

See the answer here: JSON order mixed up

You cannot and should not rely on the ordering of elements within a JSON object.

From the JSON specification at http://www.json.org/:

"An object is an unordered set of name/value pairs"

As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.

Community
  • 1
  • 1
shanet
  • 7,246
  • 3
  • 34
  • 46
4

as others have mentioned, JSONObject isn't supposed to keep the same order.

however, if you do wish to have ordered items, you can implement it yourself, and use LinkedHashMap as the container of items for your class.

android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • 2
    Because you aren't supposed to use the JSON object. You put the data into the LinkedHashMap by the order you wish, and then you can show it in the same order you've put it. – android developer Mar 02 '15 at 18:57
2

That JSONObject is actually a map of keys to values. It has no intrinsic order. If you want something ordered, you might want to look into JSONArray (but that won't have keys -> values, just values).

Ren
  • 3,395
  • 2
  • 27
  • 46