Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i sort my JSON object based on Key?

Tags:

java

json

I am creating a JSON object in which i am adding a key and a value which is an array. The value for both key and value comes from a TreeSet which has data in sorted form. However, when I insert data in my json object, it is stored randomly without any order. This is my json object currently:

{
    "SPAIN":["SPAIN","this"],
    "TAIWAN":["TAIWAN","this"],
    "NORWAY":["NORWAY","this"],
    "LATIN_AMERICA":["LATIN_AMERICA","this"]
}

and my code is:

 Iterator<String> it= MyTreeSet.iterator();

        while (it.hasNext()) {
            String country = it.next();
            System.out.println("----country"+country);
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(country);
            jsonArray.put("this);

            jsonObj.put(country, jsonArray);
        }

Is there any way I can store the data into my json object inside the while loop itself?

like image 557
AppleBud Avatar asked Jan 12 '23 02:01

AppleBud


1 Answers

Even if this post is quite old, I thought it is worth posting an alternative without GSON:

First store your keys in an ArrayList, then sort it and loop through the ArrayList of keys:

Iterator<String> it= MyTreeSet.iterator();
ArrayList<String>keys = new ArrayList();

while (it.hasNext()) {
    keys.add(it.next());
}
Collections.sort(keys);
for (int i = 0; i < keys.size(); i++) {
    String country = keys.get(i);
    System.out.println("----country"+country);
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(country);
    jsonArray.put("this");

    jsonObj.put(country, jsonArray);
}
like image 143
Christian Avatar answered Jan 22 '23 23:01

Christian