Java中對JSONArray中的對象進行排序


String jsonArrStr = "[ { \"ID\": \"135\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";

JSONArray jsonArr =JSONObject.parseArray(jsonArrStr); JSONArray sortedJsonArray = new JSONArray(); List<JSONObject> jsonValues = new ArrayList<JSONObject>(); for (int i = 0; i < jsonArr.size(); i++) { jsonValues.add(jsonArr.getJSONObject(i)); } Collections.sort( jsonValues, new Comparator<JSONObject>() { //You can change "Name" with "ID" if you want to sort by ID private static final String KEY_NAME = "ID"; @Override public int compare(JSONObject a, JSONObject b) { String valA = new String(); String valB = new String(); try { valA = (String) a.get(KEY_NAME); valB = (String) b.get(KEY_NAME); } catch (JSONException e) { //do something } return valB.compareTo(valA); //if you want to change the sort order, simply use the following: //return -valA.compareTo(valB); } }); for (int i = 0; i < jsonArr.size(); i++) { sortedJsonArray.add(jsonValues.get(i)); }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM