JSON遍历获取key的值
工具类
项目中经常用到需要通过一段json字符获取某个value,但是不确定层级。现在记录一下实现的方法
代码片
.
public class JsonUtil {
public static boolean containsKey(Object object, String key) {
if(object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
Object o = entry.getValue();
if(StrUtil.equals(entry.getKey(), key)) {
return true;
}
if(o instanceof String || o instanceof Integer || o instanceof Boolean) {
// 值
} else if(containsKey(o, key)){
return true;
}
}
}
if(object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for(int i = 0; i < jsonArray.size(); i ++) {
if (containsKey(jsonArray.get(i), key)) {
return true;
}
}
}
return false;
}
public static List<Object> getValueByKey(Object object, String key) {
List<Object> result = new ArrayList<>();
if(object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
Object o = entry.getValue();
if(ObjectUtil.isNotEmpty(o)) {
if (o instanceof String || o instanceof Integer || o instanceof Boolean) {
if (StrUtil.equals(entry.getKey(), key)) {
result.add(o);
}
// 值
} else {
result.addAll(getValueByKey(o, key));
}
}
}
}
if(object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for(int i = 0; i < jsonArray.size(); i ++) {
result.addAll(getValueByKey(jsonArray.get(i), key));
}
}
return result;
}
}