JSON工具

package com.lianzhu.filemanage.utils;

import com.alibaba.fastjson.JSONObject;

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

/**
 * JSONOBJECT排序工具
 */
public class JsonSortUtil {
    /**
     * 按指定key排序JSONObject对象集合
     *
     * @param list JSONObject对象集合
     * @param key  指定排序key
     */
    public static void sort(List<JSONObject> list, final String key) {
        Collections.sort(list, new Comparator<JSONObject>() {

            @Override
            public int compare(JSONObject a, JSONObject b) {
                return JsonSortUtil.compare(a, b, key);
            }
        });
    }


    /**
     * 按指定key降序排序JSONObject对象集合
     *
     * @param list JSONObject对象集合
     * @param key  指定排序key
     */
    public static void sortDesc(List<JSONObject> list, final String key) {
        Collections.sort(list, new Comparator<JSONObject>() {

            @Override
            public int compare(JSONObject a, JSONObject b) {
                return -1 * JsonSortUtil.compare(a, b, key);
            }
        });
    }

    /**
     * 按指定key比较两个JSONObject对象大小
     *
     * @param a   第一个JSONObject对象
     * @param b   第二个JSONObject对象
     * @param key 指定进行比较的key
     * @return <ul>
     *             <li>如果a==b,返回0</li>
     *             <li>如果a>b,返回1</li>
     *             <li>如果a<b,返回-1</li>
     *         </ul>
     */
    public static int compare(JSONObject a, JSONObject b, String key) {
        Object va = a.get(key);
        Object vb = b.get(key);

        if (null == va && null == vb) {
            return 0;
        }

        if (null == va) {
            return -1;
        }

        if (null == vb) {
            return 1;
        }

        if (va.equals(vb)) {
            return 0;
        }

        if (va instanceof Number && vb instanceof Number) {

            /* 取double值相减,兼容整数 */
            if (a.getDoubleValue(key) - b.getDoubleValue(key) > 0) {
                return 1;
            } else {
                return -1;
            }
        }

        return a.getString(key).compareToIgnoreCase(b.getString(key));
    }

}

 

posted @ 2022-08-23 21:27  余生请多指教ANT  阅读(20)  评论(0)    收藏  举报