package com.demo.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class Utils {
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
/**
* 按照JSONArray中的对象的某个字段进行排序(采用fastJson)
*
* @param jsonArrayStr json数组字符串
* @param sortkeyname 根据哪个字段进行排序
* @param order 倒序:0;非0顺序
* @return 排序后的jsonarray
*/
public static String jsonArraySortByField(String jsonArrayStr,String sortkeyname, String order) {
JSONArray sortedJsonArray = new JSONArray();
try {
JSONArray jsonArray = JSON.parseArray(jsonArrayStr);
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.size(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Collections.sort(jsonList, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject a, JSONObject b) {
String strA = new String();
String strB = new String();
String regEx="[\n`~!@#$%^&*()+=|{}':;',\\-_\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。, 、?]";
String aStr = a.getString(sortkeyname);
strA = aStr.replaceAll(regEx, "");
String bStr = b.getString(sortkeyname);
strB = bStr.replaceAll(regEx, "");
if ("0".equals(order)) {
return -strA.compareTo(strB);
}else {
return strA.compareTo(strB);
}
}
});
for (int i = 0; i < jsonArray.size(); i++) {
sortedJsonArray.add(jsonList.get(i));
}
} catch (Exception e) {
logger.error("{}",e);
}
return sortedJsonArray.toString();
}
public static void main(String[] args) {
String arystr = "[{\"score\":\"0.9627372622\",\"id\":\"103a16\",\"pic\":\"https://www.baidu.com/image/8.jpg\",\"token\":\"103a16\"},{\"score\":\"0.9312456846\",\"id\":\"88ca26\",\"pic\":\"https://www.baidu.com/image/7.jpg\",\"token\":\"88ca26\"},{\"score\":\"0.864590168\",\"id\":\"62f9af\",\"pic\":\"https://www.baidu.com/image/6.jpg\",\"token\":\"62f9af\"},{\"score\":\"0.4668337405\",\"id\":\"133c95\",\"pic\":\"https://www.baidu.com/image/5.jpg\",\"token\":\"133c95\"},{\"score\":\"0.3707543612\",\"token\":\"14f4f5\",\"id\":\"14f4f5\",\"pic\":\"https://www.baidu.com/image/4.jpg\"},{\"score\":\"0.3620336354\",\"id\":\"f93484\",\"pic\":\"https://www.baidu.com/image/3.jpg\",\"token\":\"f93484\"},{\"score\":\"0.3187969029\",\"id\":\"cf77f1\",\"pic\":\"https://www.baidu.com/image/2.jpg\",\"token\":\"cf77f1\"},{\"score\":\"0.1458527148\",\"id\":\"1dff6f\",\"pic\":\"https://www.baidu.com/image/1.jpg\",\"token\":\"1dff6f\"}]";
System.out.println(jsonArraySortByField(arystr, "score","0"));
}
}
jsonarray按指定字段进行排序
最新推荐文章于 2025-03-05 17:57:42 发布