前段时间在做json报文处理的时候,写了一个针对不同格式json转map的处理工具方法,总结记录如下:
1、单节点单层级、单节点多层级json转map
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.json.JSONTokener;
/**
* 功能:
* 1、将单/多层级的Json字符串解析为Map格式
* 2、将Map格式的数据封装成Json
*
* 避免字符串中有特殊字符而出现的错误
* @author lmb
* @version 1.0
* @date 2017-06-01
*/
public class JSONUtils {
private final static String regex = "\"([^\\\" ]+?)\":";
/**
* 一个方法解析多层json数据 json + 正则 + 递归
* @param jsonStr
* @return
*/
public static Object jsonParse(final String jsonStr) {
if (jsonStr == null) throw new NullPointerException("JsonString shouldn't be null");
try {
if (isJsonObject(jsonStr)) {
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(jsonStr);
final Map<String, Object> map = new HashMap<String, Object>();
final JSONObject jsonObject = new JSONObject(jsonStr);
// System.out.println("jsonStr = " + jsonStr);
// System.out.println("jsonObject = " + jsonObject);
try {
for (; matcher.find(); ) {
String groupName = matcher.group(1);
Object obj = jsonObject.opt(groupName);
if (isJsonObject(obj+"") || isJsonArray(obj+"")) {
matcher.region(matcher.end() + (obj+"").replace("\\", "").length(), matcher.regionEnd());
map.put(groupName, jsonParse(obj+""));
} else {
map.put(groupName, obj+"");
}
}
} catch (Exception e) {
// TODO: handle exception
}
return map;
} else if (isJsonArray(jsonStr)) {
List<Object> list = new ArrayList<Object>();
try {
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
Object object = jsonArray.opt(i);
list.add(jsonParse(object+""));
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
} catch (Exception e) {
// TODO: handle exception
}
return jsonStr;
}
/**
* To determine whether a string is JsonObject {@link org.json.JSONObject}
* @param jsonStr {@link java.lang.String}
* @return boolean
*/
private static boolean isJsonObject(final String jsonStr) {
if (jsonStr == null) return false;
return Pattern.matches("^\\{.*\\}$", jsonStr.trim());
}
/**
* To determine whether a string is JsonArray {@link org.json.JSONArray};
* @param jsonStr {@link java.lang.String}
* @return boolean
*/
private static boolean isJsonArray(final String jsonStr) {
if (jsonStr ==