Reorder the existing json

When signing the interface and splicing plaintext strings, most people agree that the input parameters need to be sorted in alphabetical order, so they wrote the method of json reordering. The central idea is to use json's built-in conversion string and sort it JSONObject.toJSONString(json, SerializerFeature.MapSortField), and finally convert it back to json.

sorting tools

package com.yulisao.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * JSON 排序
 * author yulisao
 * createDate 2023/4/14
 */
public class JsonSortUtils {
    
    

    public static void main(String[] args) {
    
    
        JSONObject json = new JSONObject();
        //JSONObject json = new JSONObject(new LinkedHashMap<>());
        json.put("bb", "23");
        json.put("aa", "zhang");
        json.put("cc", "13122223333");

        System.out.println("sort before is " + json);
        // 若json只有一层
        //String sortStr = JSONObject.toJSONString(json, SerializerFeature.MapSortField);
        // 若json有多层,且里面层的也需要进行排序 通用一些
        String sortStr = getMapSortObjectJson(json);
        JSONObject sortJson = JSONObject.parseObject(sortStr);
        System.out.println("sort after is " + sortJson);
    }
    /**
     * JSONObject转换为排序后的字符串
     *
     * @param jsonObject
     * @return
     */
    private static String getMapSortObjectJson(JSONObject jsonObject) {
    
    
        if (null == jsonObject) {
    
    
            return "";
        }
        Set<String> keySet = jsonObject.keySet();
        Iterator<String> keys = keySet.iterator();
        while (keys.hasNext()) {
    
    
            String key = keys.next();
            String value = jsonObject.getString(key);
            // 非 JSONArray、 JSONObject 则跳过
            if (!JSONObject.isValid(value)) {
    
    
                continue;
            }
            Object object = JSONObject.parse(value);
            if (null != object && object instanceof JSONObject) {
    
    
                JSONObject valueJsonObject = JSONObject.parseObject(value);
                String jsonValue = getMapSortObjectJson(valueJsonObject);
                jsonObject.fluentPut(key, JSONObject.parseObject(jsonValue));
            }
            if (null != object && object instanceof JSONArray) {
    
    
                JSONArray jsonArray = JSONArray.parseArray(value);
                String jsonValue = getMapSortArrayJson(jsonArray);
                jsonObject.fluentPut(key, JSONArray.parseArray(jsonValue));
            }
        }
        return JSONObject.toJSONString(jsonObject, SerializerFeature.MapSortField);
    }
    /**
     * JSONArray转换为排序后的字符串
     *
     * @param jsonArray
     * @return
     */
    private static String getMapSortArrayJson(JSONArray jsonArray) {
    
    
        JSONArray resultArray = new JSONArray();
        for (int index = 0; index < jsonArray.size(); index++) {
    
    
            // 里面的对象转化为JSONObject
            String value = jsonArray.getString(index);
            if (JSONObject.isValid(value)) {
    
    
                resultArray.add(JSONObject.parse(getMapSortFieldJson(value)));
                continue;
            }
            resultArray.add(value);
        }
        return JSONArray.toJSONString(resultArray, SerializerFeature.MapSortField);
    }

    /**
     * JSON字符串排序
     *
     * @param json 原JSON字符串
     * @return 排序后的JSON字符串
     */
    public static String getMapSortFieldJson(String json) {
    
    
        if (StringUtils.isEmpty(json)) {
    
    
            return json;
        }
        Object object = JSONObject.parse(json);
        if (null != object && object instanceof JSONObject) {
    
    
            JSONObject jsonObject = JSONObject.parseObject(json);
            json = getMapSortObjectJson(jsonObject);
        }
        if (null != object && object instanceof JSONArray) {
    
    
            JSONArray jsonArray = JSONArray.parseArray(json);
            json = getMapSortArrayJson(jsonArray);
        }
        return json;
    }

}

operation result

sort before is {
    
    "bb":"23","aa":"zhang","cc":"13122223333"}
sort after is {
    
    "aa":"zhang","bb":"23","cc":"13122223333"}

Other Notes
The bottom layer of JSONObject is a Map structure, the default is HashMap, and it can also be changed to LinkedHashMap, there are some differences in the order of the two. The way to change to LinkedHashMap is

JSONObject json = new JSONObject(true); 或者
JSONObject json = new JSONObject(new LinkedHashMap<>());

But if it is of LinkedHashMap type, the above tool class will be invalid and will not work

Guess you like

Origin blog.csdn.net/qq_29539827/article/details/130408309