JSON根据KEY进行排序(JAVA实现)

有时候需要对JSON进行排序,然后进行对比

package com.taxbureau.tax.util;
 
 
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: 维斯
 * @Date: 2022/6/30 14:55
 * @Description: Json排序工具
 * @Version: v1.0
 */
public class JsonSortUtil {
    /**
     * 对单词列表进行冒泡排序
     * 直接操作对象地址 无需返回
     *
     * @param words ["name","age"]
     */
    private static void wordSort(ArrayList<String> words) {
        for (int i = words.size() - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (words.get(j).compareToIgnoreCase(words.get(j + 1)) > 0) {
                    String temp = words.get(j);
                    words.set(j, words.get(j + 1));
                    words.set(j + 1, temp);
                }
            }
        }
    }

    /**
     * 对单层json排序
     *
     * @param json
     */
    private static JSONObject getAloneKeys(JSONObject json) {
        ArrayList<String> aloneKeys = new ArrayList<>();
        for (String key : json.keySet()) {
            aloneKeys.add(key);
        }
        // 排序
        JsonSortUtil.wordSort(aloneKeys);
        // 整理排序后的json
        JSONObject newJson = new JSONObject(new LinkedHashMap<>());
        for (String key : aloneKeys) {
            newJson.put(key, json.get(key));
        }
        return newJson;
    }

    /**
     * 递归每一层(当前是判断下一层是JSONObject类型的场景)
     *
     * @param json
     * @return
     */
    private static JSONObject getAloneKeysRec(JSONObject json) {
        JSONObject newJson = getAloneKeys(json);

        for (Map.Entry<String, Object> entry : newJson.entrySet()) {
            // JSONObject类型
            if (entry.getValue() != null && entry.getValue().getClass().equals(JSONObject.class)) {
                newJson.put(entry.getKey(), getAloneKeysRec((JSONObject) entry.getValue()));
            }
        }

        return newJson;
    }

    /**
	     * 对JSONObject的key根据首字母排序 若首字母相同对比下一个字母 依次类推
	     * 备注:当前未覆盖JSONArray的场景
     *
     * @param json
     * @return 排序后的新json
     */
    public static JSONObject startSort(JSONObject json) {
        // 第1层
        JSONObject jsonAlone = getAloneKeys(json);
        // 第2-n层
        for (Map.Entry<String, Object> entry : jsonAlone.entrySet()) {
            // 这里仅判断JSONObject类型的场景(若需要覆盖JSONArray场景 对应添加即可)
            if (entry.getValue().getClass().equals(JSONObject.class)) {
                jsonAlone.put(entry.getKey(), getAloneKeysRec((JSONObject) entry.getValue()));
            }
        }
        return jsonAlone;
    }
    
    /**
	     * 对JSONObject的key首字母大写
	 *
	 * @param jsonStr
	 * @return 
	 */
    public static String convertKeysToUpperCase(String jsonStr) throws Exception{
         ObjectMapper objectMapper = new ObjectMapper();
         JsonNode jsonNode = objectMapper.readTree(jsonStr);

         ObjectNode modifiedJsonNode = objectMapper.createObjectNode();

         Iterator<String> fieldNames = jsonNode.fieldNames();
         while (fieldNames.hasNext()) {
             String fieldName = fieldNames.next();
             String modifiedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
             modifiedJsonNode.set(modifiedFieldName, jsonNode.get(fieldName));
         }

         jsonNode = modifiedJsonNode;

        return jsonNode.toString();
    }
}

测试代码

public static void main(String[] args) {
		
		String json = "";
		try {

			System.out.println(JsonSortUtil.startSort(json).toJSONString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

要根据key首字母排序JSON,可以使用Java中的JSONObject和TreeMap来实现。首先,将JSON字符串解析为JSONObject对象。然后,创建一个TreeMap对象,并通过迭代JSONObjectkeySet获取所有的key。将这些key添加到TreeMap中,由于TreeMap会根据其自然排序对元素进行排序,所以这些key会按照首字母进行排序。最后,通过遍历TreeMap的entrySet,可以获取到按首字母排序key和对应的value,可以将其重新组装成一个新的JSON对象。 下面是具体的代码实现: ```java import org.json.JSONObject; import java.util.Iterator; import java.util.TreeMap; public class Main { public static void main(String[] args) { String jsonStr = "{\"name\": \"John\", \"age\": 30, \"address\": \"New York\"}"; // 解析JSON字符串为JSONObject对象 JSONObject jsonObject = new JSONObject(jsonStr); // 创建TreeMap并将JSONObjectkey按首字母排序 TreeMap<String, Object> sortedMap = new TreeMap<>(); Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); sortedMap.put(key, jsonObject.get(key)); } // 构建新的JSONObject对象 JSONObject sortedJson = new JSONObject(); for (String key : sortedMap.keySet()) { sortedJson.put(key, sortedMap.get(key)); } System.out.println(sortedJson.toString()); } } ``` 以上代码会输出按首字母排序后的JSON字符串: ```json {"address":"New York","age":30,"name":"John"} ``` 这样就实现了根据key首字母排序JSON的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liberty888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值