package com.yl.box.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import java.util.*;
public class JsonUtils {
public static Map<String, Object> jsonToMap(String jsonStr) {
Map<String, Object> treeMap = new TreeMap();
JSONObject json = JSONObject.parseObject(jsonStr, Feature.OrderedField);
Iterator<String> keys = json.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
Object value = json.get(key);
if (json.get(key) == null || value == null) {
continue;
}
if (value instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) value;
List<Object> arrayList = new ArrayList<>();
for (Object object : jsonArray) {
if (object instanceof JSONObject) {
object = jsonToMap(object.toString());
}
arrayList.add(object);
}
treeMap.put(key, arrayList);
} else {
boolean flag = isJSONValid(value.toString());
if (flag) {
value = jsonToMap(value.toString());
}
treeMap.put(key, value);
}
}
return treeMap;
}
public final static boolean isJSONValid(String json) {
try {
if (null == JSONObject.parseObject(json)) {
return false;
}
} catch (Exception ex) {
return false;
}
return true;
}
}