引用ali的fastjson,将json转换成map,代码如下:
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
/**
* @author lelontar
* @ClassName: Json2MapUtil
* @ProjectName user-service
* @Description: 将json字符串转换成map
* @date 2019/2/18/14:27
*/
public class Json2MapUtil {
/**
* 将json字符串转为Map结构
* @param json
* @return 返回一个map
*/
public static HashMap<String, Object> json2Map(String json) {
HashMap<String, Object> map = new HashMap<>();
if(jsonStr != null && !"".equals(json)){
//最外层解析
JSONObject json = JSONObject.parseObject(json);
for (Object k : json.keySet()) {
Object v = json.get(k);
//判断是否是数组,如果是数组继续解析
if (v instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator it = ((JSONArray) v).iterator();
while (it.hasNext()) {
Object jsonObj = it.next();
list.add(json2Map(jsonObj.toString()));
}
map.put(k.toString(), list);
} else {
map.put(k.toString(), v);
}
}
return map;
}else{
return null;
}
}
}