When JsonObject's keys are iterated they aren't in the same order as in the response from the server

I have a very large response from server of JSON string. I converted it to JSON object and then get the keys and iterate it.

The problem is that when I iterate it isnt in the same order as in response from server.

Next then I apply another method by adding all the keys in List<String> and the sort it and then get the iterator of that but still it isn't as I required (as in response).

Code example is here:

JSONObject jsonObject = new JSONObject(responseString);
    Iterator<String> myIter = jsonObject.keys();


    List<String> sortKey = new ArrayList<String>();

    while(myIter.hasNext()){
        sortKey.add(myIter.next());
    }
    Collections.sort(sortKey);

Answers


The order of the keys of a JSON object is not supposed to be meaningful. If you want a specific order, you should use an array, not an object.

Your Java code sorts the keys alphabetically. There is no way to get the initial ordering of the keys in the object.

Reference 1:

The order of the keys is undefined

Reference 2:

An object is an unordered set of name/value pairs


You can use Sorted map to put keys and values into. Something like this

 public static List listFromJsonSorted(JSONObject json) {
    if (json == null) return null;
    SortedMap map = new TreeMap();
    Iterator i = json.keys();
    while (i.hasNext()) {
        try {
            String key = i.next().toString();
            JSONObject j = json.getJSONObject(key);
            map.put(key, j);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return new LinkedList(map.values());
}

I came across this similar problem while working on section in my android app which displays a list of 1024+ websites alphabetically. Since the json traversal was not in sorted order , I just inserted the json values during traversal into a table ( I m using list adapters in my app) and obtained sorted list of websites with cursor.

So if you are saving what you are fetching from server, you can just query your database to sort the values in the order your want.


Need Your Help

Complex Type Array nusoap and iPhone parsing

iphone nusoap complextype

When I am accessing an Array of data that is returned from nusoap I encounter duplicate tags. I tried with complex type, but it is not working the way I require i.e, enclosing in specific tags ins...

How to handle errors/exceptions when calling an external API in Ruby on Rails?

ruby-on-rails api exception-handling ruby-on-rails-3.1 error-handling

I'm interacting with CampaignMonitor's API using the ruby wrapper (createsend-ruby) and I'm just wondering what you'd recommend as far as error/exception handling. I was thinking of just using begin/