网上也蛮多例子的,但是业务上的json字符串过于复杂,非常难解析,后来在网上找了些资料,在基础之上加以改进,目前使用没有太大的问题,解析速度一般般,但是应付大部分场景也够用了,如果对性能要求高,数据量极大的场景不适合使用,下面贴代码:
pom依赖:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
代码:
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import java.util.*;
/**
* @描述: Json2Map
* @公司:
* @作者: 万人往
* @版本: 1.0.0
* @日期: 2020-01-19 15:02:44
*/
public class Json2Map {
/**
* 将json字符串转为Map结构
* 如果json复杂,结果可能是map嵌套map
*
* @param jsonStr 入参,json格式字符串
* @return 返回一个map
*/
public static Map<String, Object> json2Map(String jsonStr) {
Map<String, Object> map = new HashMap<>();
if (StringUtils2.isNotEmpty(jsonStr)) {
//jsonStr = Json2Map.replaceBlank(jsonStr);
//最外层解析
JSONObject json = JSONObject.fromObject(jsonStr);
for (Object k : json.keySet()) {
Object v = json.get(k);
if (JSONNull.getInstance().equals(v)) {
map.put(k.toString(), "");
continue;
}
//如果内层还是数组的话,继续解析
if (v instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> it = ((JSONArray) v).iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj == null || JSONNull.getInstance().equals(obj)) {
continue;
}
JSONObject json2 = (JSONObject) obj;
if (null == json2 || json2.isNullObject() || json2.isEmpty()) {
continue;
} else {
list.add(json2Map(json2.toString()));
}
}
map.put(k.toString(), list);
} else {
map.put(k.toString(), v);
}
}
return map;
} else {
return null;
}
}
}