简体   繁体   中英

JAVA Sort JSONObject (String,Int) in descending order

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 ?)

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();
    }
}

}

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM