package com.btzh.mis.dep.data.center.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestSort { public static void main(String[] args) { String jsonArrStr = "[ { \"START_TIME\": \"2016-05-25\", \"Name\": \"Fargo Chan\" },{ \"START_TIME\": \"2016-05-23\", \"Name\": \"Aaron Luke\" },{ \"START_TIME\": \"2016-05-26\", \"Name\": \"Dilip Singh\" }]"; System.out.print(jsonArraySort(jsonArrStr,"START_TIME")); } public static String jsonArraySort(String jsonArrStr,String key) { JSONArray jsonArr = JSON.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>() { @Override public int compare(JSONObject a, JSONObject b) { String valA = new String(); String valB = new String(); try { // 这里是a、b需要处理的业务,需要根据你的规则进行修改。 String aStr = a.getString(key); valA = aStr.replaceAll("-",""); String bStr = b.getString(key); valB = bStr.replaceAll("-", ""); } catch (JSONException e) { // do something } return -valA.compareTo(valB); // 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)); } return sortedJsonArray.toString(); } }
在数组中通过关键字进行json排序
最新推荐文章于 2023-07-04 22:15:00 发布