Java 多层 JSON 按键排序 - 代码示例及解析
以下是使用 Java 语言按照 key 排序多层 JSON 的示例代码:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import java.util.TreeMap;
public class JsonSorter {
public static void main(String[] args) throws JSONException {
// 示例 JSON 字符串
String jsonString = '{"name":"John","age":30,"cars":["Ford","BMW","Fiat"],"address":{"street":"Main Street","city":"New York","state":"NY","zip":"10001"}}';
// 将 JSON 字符串转换为 JSONObject 对象
JSONObject jsonObject = new JSONObject(jsonString);
// 创建一个 TreeMap 来保存按照 key 排序后的 JSON 对象
TreeMap<String, Object> sortedJson = new TreeMap<>();
// 遍历 JSON 对象
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = jsonObject.get(key);
// 如果 value 是 JSONObject,则递归调用 sortJson() 方法
if (value instanceof JSONObject) {
value = sortJson((JSONObject)value);
}
// 如果 value 是 JSONArray,则递归调用 sortJson() 方法对每个元素进行排序
else if (value instanceof JSONArray) {
JSONArray jsonArray = (JSONArray)value;
JSONArray sortedArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
Object element = jsonArray.get(i);
if (element instanceof JSONObject) {
element = sortJson((JSONObject)element);
}
sortedArray.put(element);
}
value = sortedArray;
}
// 将 key 和 value 添加到 sortedJson 中
sortedJson.put(key, value);
}
// 将 sortedJson 转换为 JSONObject 对象并输出
JSONObject sortedJsonObject = new JSONObject(sortedJson);
System.out.println(sortedJsonObject.toString());
}
// 对 JSONObject 对象进行排序
private static JSONObject sortJson(JSONObject jsonObject) throws JSONException {
TreeMap<String, Object> sortedJson = new TreeMap<>();
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
value = sortJson((JSONObject)value);
}
else if (value instanceof JSONArray) {
JSONArray jsonArray = (JSONArray)value;
JSONArray sortedArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
Object element = jsonArray.get(i);
if (element instanceof JSONObject) {
element = sortJson((JSONObject)element);
}
sortedArray.put(element);
}
value = sortedArray;
}
sortedJson.put(key, value);
}
return new JSONObject(sortedJson);
}
}
该示例代码将输入的 JSON 字符串按照 key 进行排序后输出。在遍历 JSON 对象时,如果 value 是 JSONObject,则递归调用 sortJson() 方法对其进行排序;如果 value 是 JSONArray,则递归调用 sortJson() 方法对每个元素进行排序。最后将排序后的 JSON 对象转换为 JSONObject 对象并输出。
原文地址: https://www.cveoy.top/t/topic/oORZ 著作权归作者所有。请勿转载和采集!