如何在JAVA中对JSONArray进行排序

前端之家收集整理的这篇文章主要介绍了如何在JAVA中对JSONArray进行排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Android how to sort JSONArray of JSONObjects6
如何按对象的字段排序对象的JSONArray?

输入:

  1. [
  2. { "ID": "135","Name": "Fargo Chan" },{ "ID": "432","Name": "Aaron Luke" },{ "ID": "252","Name": "Dilip Singh" }
  3. ];

所需输出(按“名称”字段排序):

  1. [
  2. { "ID": "432","Name": "Dilip Singh" }
  3. { "ID": "135",];

解决方法

尝试这个:
  1. //I assume that we need to create a JSONArray object from the following string
  2. String jsonArrStr = "[ { \"ID\": \"135\",\"Name\": \"Fargo Chan\" },{ \"ID\": \"432\",\"Name\": \"Aaron Luke\" },{ \"ID\": \"252\",\"Name\": \"Dilip Singh\" }]";
  3.  
  4. JSONArray jsonArr = new JSONArray(jsonArrStr);
  5. JSONArray sortedJsonArray = new JSONArray();
  6.  
  7. List<JSONObject> jsonValues = new ArrayList<JSONObject>();
  8. for (int i = 0; i < jsonArr.length(); i++) {
  9. jsonValues.add(jsonArr.getJSONObject(i));
  10. }
  11. Collections.sort( jsonValues,new Comparator<JSONObject>() {
  12. //You can change "Name" with "ID" if you want to sort by ID
  13. private static final String KEY_NAME = "Name";
  14.  
  15. @Override
  16. public int compare(JSONObject a,JSONObject b) {
  17. String valA = new String();
  18. String valB = new String();
  19.  
  20. try {
  21. valA = (String) a.get(KEY_NAME);
  22. valB = (String) b.get(KEY_NAME);
  23. }
  24. catch (JSONException e) {
  25. //do something
  26. }
  27.  
  28. return valA.compareTo(valB);
  29. //if you want to change the sort order,simply use the following:
  30. //return -valA.compareTo(valB);
  31. }
  32. });
  33.  
  34. for (int i = 0; i < jsonArr.length(); i++) {
  35. sortedJsonArray.put(jsonValues.get(i));
  36. }

排序的JSONArray现在存储在sortedJsonArray对象中.

猜你在找的Java相关文章