import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* JSON解析
* @author Alien
* @since 2018-04-05
*/
public class JSONReader {
/**
* JSON对象类型: 映射类型、数组类型、非法类型
* @author Alien
* @since 2018-04-05
*/
public enum JSONTYPE {
MAP, ARRAY, UNKONW;
}
/**
* 根据指定规则求出JSON字符串的值
* @param json json类型的字符串
* @param rules 求值规则, 如: key1.[0]key2.key3
* @return 规则正确的情况下返回对应的值, 规则不正确返回空串
*/
public String evaluate (String json, String rules) {
if (isNull(json) || isNull(rules))
return "";
String key = rules, value = "";
int dotIdx = rules.indexOf(".");
JSONTYPE jsonType = getJSONType(json);
if ( jsonType != JSONTYPE.UNKONW) {
JSONObject jsonObject = null;
JSONArray jsonArray = null;
if (dotIdx != -1) {
key = rules.substring(0, dotIdx);
rules = rules.substring(dotIdx + 1, rules.length());
}
try {
Matcher mIdx = Pattern.compile("(?<=\\[)\\d+(?=\\])").matcher(key);
Matcher mKey = Pattern.compile("(?<=\\]).*").matcher(key);
if (mIdx.find() && mKey.find() && jsonType == JSONTYPE.ARRAY) { //key传入数组下标, 且json是个数组
int idx = Integer.valueOf(mIdx.group());
key = mKey.group();
jsonArray = JSONArray.fromObject(json);
json = jsonArray.getString(idx);
}
jsonObject = JSONObject.fromObject(json);
value = jsonObject.getString(key);
}
catch (Exception e) {
return "";
}
}
else
return "";
if (dotIdx == -1)
return value;
else
return evaluate(value, rules);
}
/**
* 获取JSON对象类型
* @param json 被获取的JSON字符串
* @return JSON对象类型: 映射类型、数组类型、非法类型
*/
public JSONTYPE getJSONType(String json) {
if (json.startsWith("{") && json.endsWith("}"))
return JSONTYPE.MAP;
if (json.startsWith("[") && json.endsWith("]"))
return JSONTYPE.ARRAY;
return JSONTYPE.UNKONW;
}
/**
* 判断是否为空。包括null、字符串null、空字符串、
* @param str 需判断的字符串
* @return 为空:true, 非空: false
*/
public boolean isNull(String str) {
str = (str + "").trim().toLowerCase();
if (str.isEmpty() || "null".equals(str))
return true;
else
return false;
}
}
Java解析JSON
最新推荐文章于 2024-07-29 21:09:19 发布