1

I have a JSONObject which I get via an API. It is like this:

    {
     "wash_method": 305,
     "fragrance": 1156,
     "sweater_type": 260,
     "dial_color": 66475,
     "charger_type": 2581,
     "pen_drives_interface": 563,
      "watches_type": 66475,
      "processor": 3270,
      "frame_material": 1211,
      "dial_shape": 66475,
      "os": 3308
     }

I want to sort this on the basis of values to get a result like this:

    {
     "dial_shape": 66475,
     "dial_color": 66475,
     "watches_type": 66475,
      "os": 3308,
      "processor": 3270,
      "charger_type": 2581,
      "frame_material": 1211,
      "fragrance": 1156,
      "pen_drives_interface": 563,
     "wash_method": 305,
     "sweater_type": 260,      
     }

As you can see top 3 items have similar value so they can get arranged in any way.
How can I do this? (Is there a way to do it with minimum complexity ?)

7
  • 1
    JSON object has nor notion of "sorting" Commented Oct 26, 2016 at 10:19
  • It has to be done by the API developer before giving u the response Commented Oct 26, 2016 at 10:23
  • 2
    JSONObject is an unordered set of name/value pairs. So you can not sort them. Rather you can parse the Json and store in List and sort the list as per you need. Commented Oct 26, 2016 at 10:26
  • 2
    @Baba I need to extract the data and pick top 15 sorted items (key,value) into a list. ? Commented Oct 26, 2016 at 10:30
  • 1
    Why don't you extract the data then sort it?? Commented Oct 26, 2016 at 11:36

2 Answers 2

2

Here is the solution of your problem. I hope this will help.

import org.json.JSONException;

import org.json.JSONObject;

import java.util.*;

public class sample {
private static class MyModel {
    String key;
    int value;

    MyModel(String key, int value) {
        this.key = key;
        this.value = value;
    }
}

public static void main(String[] args) {
    List<MyModel> list = new ArrayList<>();

    try {
        //here is you json object
        JSONObject obj = new JSONObject();
        obj.put("name1", 29);
        obj.put("name2", 26);
        obj.put("name3", 29);
        obj.put("name4", 27);

        //parsing your json
        Iterator<?> keys = obj.keys();
        MyModel objnew;
        while (keys.hasNext()) {
            String key = (String) keys.next();
            objnew = new MyModel(key, obj.optInt(key));
            list.add(objnew);
        }

        //sorting the values
        Collections.sort(list, new Comparator<MyModel>() {
            @Override
            public int compare(MyModel o1, MyModel o2) {
                return Integer.compare(o2.value, o1.value);
            }
        });
        //print out put
        for (MyModel m : list) {
            System.out.println(m.key + " : " + m.value);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

}

Sign up to request clarification or add additional context in comments.

3 Comments

You can see in code. It is a class which will store key/value after parsing you json.
Thanks ! This worked perfectly. But one question though. Integer.compare(o2.value, o1.value) this method works only when API level is 19 or above. What is the alternative for below API 19 devices?
Write you compare logic here : return o2.value==o1.value ? 0 : (o2.value < o1.value ? -1 : 1);
0

Try implementing this one

public class SomeClass {

    /**
     * Sorts the given JSONObject
     *
     * @param jsonObject
     * @return jsonObject sorted in descending order
     * @throws JSONException
     */
    public JSONObject sortJSONObject(JSONObject jsonObject) throws JSONException {

        ArrayList<SomeChildClass> alstSomeChildClass = new ArrayList<>();

        Iterator<String> keys = jsonObject.keys();

        while (keys.hasNext()) {
            SomeChildClass someChildClass = new SomeChildClass();
            someChildClass.key = keys.next();
            someChildClass.value = jsonObject.getString(someChildClass.key);
            alstSomeChildClass.add(someChildClass);
        }

        // Sort the Collection
        Collections.sort(alstSomeChildClass);

        JSONObject sortedJsonObject = new JSONObject();
        for (SomeChildClass someChildClass : alstSomeChildClass)
            sortedJsonObject.put(someChildClass.key, someChildClass.value);

        return sortedJsonObject;
    }

    private class SomeChildClass implements Comparable<SomeChildClass> {

        private String key;
        private String value;

        @Override
        public int compareTo(@NonNull SomeChildClass target) {

            int currentVal = Integer.parseInt(value);
            int targetVal = Integer.parseInt(target.value);

            return (currentVal < targetVal) ? 1 : ((currentVal == targetVal) ? 0 : -1);
        }
    }
}

UPDATE

String json = "{\n" +
            "     \"wash_method\": 305,\n" +
            "     \"fragrance\": 1156,\n" +
            "     \"sweater_type\": 260,\n" +
            "     \"dial_color\": 66475,\n" +
            "     \"charger_type\": 2581,\n" +
            "     \"pen_drives_interface\": 563,\n" +
            "      \"watches_type\": 66475,\n" +
            "      \"processor\": 3270,\n" +
            "      \"frame_material\": 1211,\n" +
            "      \"dial_shape\": 66475,\n" +
            "      \"os\": 3308\n" +
            "     }";

    try {
        JSONObject object = new SomeClass().sortJSONObject(new JSONObject(json));
        Log.e("JSON", object.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

2 Comments

This is not sorting it. Returning the same result.
Actually Above KitKat API level I do not even need to sort the JSONObject. But when I use a kitkat level phone I need to sort and the method you suggested doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.