转换复杂的JSON对象为Map对象
此文章为转载学习:
https://blog.youkuaiyun.com/u010999809/article/details/80727640
public class Json2Map {
/**
*
* 描述: 转换复杂的JSON对象Map对象
*/
public static Map<String, String> json2Map(String jsonStr) {
System.out.println(jsonStr);
Map<String, String> map = new HashMap<String, String>();
// 外层解析
JSONObject json = JSONObject.fromObject(jsonStr);
for (Object k : json.keySet()) {
Object v = json.get(k);
// 如果内层还是数组的话,继续解
if (v instanceof JSONArray) {
if(((JSONArray) v).size()==0) {
System.out.println("为空"); //数组是否为空
}else if(((((JSONArray) v).get(0)) instanceof Integer)) { //第一个是否为整数
System.out.println(((JSONArray) v).get(0));
}
else {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
//System.out.println(((JSONArray) v).getInt(1));
Iterator<JSONObject> it = ((JSONArray) v).iterator();
while (it.hasNext()) {
String json2 = it.next().toString();
//JSONObject json2 = it.next();
list.add(json2Map(json2.toString())); //迭代查看里边是否还是jsonobject
}
map.put(k.toString(),list.toString());
//map.put(k.toString(), list);
}
} else {
map.put(k.toString(), v.toString());
}
}
return map;
}