你的位置:首页 > 软件开发 > Java > JsonArray中的jsonobject对象排序问题

JsonArray中的jsonobject对象排序问题

发布时间:2017-12-04 23:00:08
package com.run.horus.earlywaring.common;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.uti ...

package com.run.horus.earlywaring.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class SortJsonArray {

    
    public  static JSONArray  sortJsonArray(JSONArray array){
        
        
            JSONArray sortedJsonArray = new JSONArray();
            List<JSONObject> jsonValues = new ArrayList<JSONObject>();
            for (int i = 0; i < array.size(); i++) {
                jsonValues.add(array.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 {
                        // 这里是a、b需要处理的业务,需要根据你的规则进行修改。
                        String aStr = a.getString(KEY_NAME);
                        valA = aStr.replaceAll("-", "");
                        String bStr = b.getString(KEY_NAME);
                        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 < array.size(); i++) {
                sortedJsonArray.add(jsonValues.get(i));
            }
            return sortedJsonArray;

    }
}
原文章链接

 

原标题:JsonArray中的jsonobject对象排序问题

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。