【问题标题】:JAVA Sort JSONObject (String,Int) in descending orderJAVA 按降序对 JSONObject (String,Int) 进行排序
【发布时间】:2016-10-26 10:18:17
【问题描述】:

我有一个通过 API 获得的 JSONObject。 是这样的:

    {
     "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
     }

我想根据值对其进行排序以获得如下结果:

    {
     "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,      
     }

如您所见,前 3 项具有相似的价值,因此可以以任何方式排列。
我怎样才能做到这一点? (有没有办法以最小的复杂性做到这一点?)

【问题讨论】:

  • JSON 对象没有“排序”的概念
  • API 开发人员必须在给您回复之前完成此操作
  • JSONObject 是一组无序的名称/值对。所以你不能对它们进行排序。相反,您可以解析 Json 并存储在 List 中,并根据需要对列表进行排序。
  • @Baba 我需要提取数据并将前 15 个排序项(键、值)放入列表中。 ?
  • 为什么不提取数据然后排序呢??

标签: java android json sorting jsonobject


【解决方案1】:

这是您问题的解决方案。我希望这会有所帮助。

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

}

【讨论】:

  • 你可以在代码中看到。它是一个在解析你的 json 后将存储键/值的类。
  • 谢谢!这非常有效。但是有一个问题。 Integer.compare(o2.value, o1.value) 此方法仅在 API 级别为 19 或更高时有效。 API 19 以下设备的替代方案是什么?
  • 在这里写你比较逻辑:return o2.value==o1.value ? 0 : (o2.value
【解决方案2】:

尝试实现这个

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

更新

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

【讨论】:

  • 这不是排序。返回相同的结果。
  • 实际上高于 KitKat API 级别我什至不需要对 JSONObject 进行排序。但是当我使用kitkat级别的手机时,我需要进行排序,而您建议的方法不起作用。
猜你喜欢
  • 2023-04-07
  • 2011-11-16
  • 2011-08-12
  • 1970-01-01
  • 2022-11-17
  • 2011-02-09
  • 2011-03-25
相关资源
最近更新 更多