排序 json数组数据 2个string同时数据顺序排序

比较方法及方法调用

 1 import java.util.ArrayList;
 2 import java.util.Collections;
 3 import java.util.Comparator;
 4 import java.util.List;
 5 import com.alibaba.fastjson.JSON;
 6 import com.alibaba.fastjson.JSONArray;
 7 import com.alibaba.fastjson.JSONException;
 8 import com.alibaba.fastjson.JSONObject;
 9 import com.alibaba.fastjson.parser.deserializer.ParseProcess;
10 
11 /**
12  * Java中对JSONArray中的对象的某个字段进行排序
13  * 
14  * @author lijianbo
15  * @version 1.0
16  *
17  */
18 public class Test1 implements ParseProcess {
19 
20     public static void main(String[] args) {
21         String jsonArrStr = "[ { \"ID\": \"2016-05-25\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"2016-05-23\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"2016-05-26\", \"Name\": \"Dilip Singh\" }]";
22         System.out.println("排序前:"+jsonArrStr);
23         String jsonArraySort = jsonArraySort(jsonArrStr);
24         System.out.println("排序后:"+jsonArraySort);
25     }
26 
27     /**
28      * 按照JSONArray中的对象的某个字段进行排序(采用fastJson)
29      * 
30      * @param jsonArrStr
31      *            json数组字符串
32      * 
33      */
34     public static String jsonArraySort(String jsonArrStr) {
35         JSONArray jsonArr = JSON.parseArray(jsonArrStr);
36         JSONArray sortedJsonArray = new JSONArray();
37         List<JSONObject> jsonValues = new ArrayList<JSONObject>();
38         for (int i = 0; i < jsonArr.size(); i++) {
39             jsonValues.add(jsonArr.getJSONObject(i));
40         }
41         Collections.sort(jsonValues, new Comparator<JSONObject>() {
42             // You can change "Name" with "ID" if you want to sort by ID
43             private static final String KEY_NAME = "ID";
44 
45             @Override
46             public int compare(JSONObject a, JSONObject b) {
47                 String valA = new String();
48                 String valB = new String();
49                 try {
50                     // 这里是a、b需要处理的业务,需要根据你的规则进行修改。
51                     String aStr = a.getString(KEY_NAME);
52                     valA = aStr.replaceAll("-", "");
53                     String bStr = b.getString(KEY_NAME);
54                     valB = bStr.replaceAll("-", "");
55                 } catch (JSONException e) {
56                     // do something
57                 }
58                 return -valA.compareTo(valB);
59                 // if you want to change the sort order, simply use the following:
60                 // return -valA.compareTo(valB);
61             }
62         });
63         for (int i = 0; i < jsonArr.size(); i++) {
64             sortedJsonArray.add(jsonValues.get(i));
65         }
66         return sortedJsonArray.toString();
67     }
68 
69 }

猜你喜欢

转载自www.cnblogs.com/wujianbo123/p/12322847.html