如果是希望最终比较字符串,可以先处理一下原字符串:重新按照一定规则排列对象的key,比如题主前面说的:
要实现的效果就是将A和B的所有键都按字母顺序排序一遍,怎么实现?
核心原理就是用TreeMap保证对象的key按照字典升序排列
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String A = "[\n" +
" {\n" +
" \"Field\":\"id\",\n" +
" \"Type\":\"int(11)\",\n" +
" \"Null\":\"NO\",\n" +
" \"Extra\":\"auto_increment\",\n" +
" \"Key\":\"PRI\"\n" +
" },\n" +
" {\n" +
" \"Field\":\"app_id\",\n" +
" \"Type\":\"varchar(8)\",\n" +
" \"Null\":\"YES\",\n" +
" \"Extra\":\"\",\n" +
" \"Key\":\"\"\n" +
" }\n" +
"]";
String B = "[\n" +
" {\n" +
" \"Field\":\"id\",\n" +
" \"Type\":\"int(11)\",\n" +
" \"Null\":\"NO\",\n" +
" \"Key\":\"PRI\",\n" +
" \"Extra\":\"auto_increment\"\n" +
" },\n" +
" {\n" +
" \"Field\":\"app_id\",\n" +
" \"Type\":\"varchar(8)\",\n" +
" \"Null\":\"YES\",\n" +
" \"Key\":\"\",\n" +
" \"Extra\":\"\"\n" +
" }\n" +
"]";
String sortedKeyA = sortedKeyArray(JSON.parseArray(A));
String sortedKeyB = sortedKeyArray(JSON.parseArray(B));
System.out.println(sortedKeyA);
System.out.println("---------------------------");
System.out.println(sortedKeyB);
}
private static String sortedKeyArray(JSONArray array) {
List<Map<String, Object>> list = new ArrayList<>();
for (Object o : array) {
JSONObject json = JSON.parseObject(JSON.toJSONString(o));
Map<String, Object> sortedKeyMap = new TreeMap<>(json);
list.add(sortedKeyMap);
}
return JSON.toJSONString(list, JSONWriter.Feature.PrettyFormat);
}
}
输出结果: