开篇说明
如果在这里获得过启发和思考,希望点赞支持!对于内容有不同的看法欢迎来信交流。
技术栈 >> java
邮箱 >> 15673219519@163.com
描述介绍
根据JSONObject中字段的名称,优雅获取深层属性值
- 使用示例,取error_entry的数量。JSON的层次结构如下 aggregations.3.buckets.[key=error_entry].doc_count
/*
{
"took": 3043,
"timed_out": false,
"_shards": {
"total": 7,
"successful": 7,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 38,
"relation": "eq"
},
"max_score": null,
"hits": [
]
},
"aggregations": {
"3": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "error_entry",
"doc_count": 34
},
{
"key": "error_patch",
"doc_count": 4
}
]
}
}
}
*/
public static void main(String[] args) {
String jsonStr = "{\"took\":3043,\"timed_out\":false,\"_shards\":{\"total\":7,\"successful\":7,\"skipped\":0,\"failed\":0},\"hits\":{\"total\":{\"value\":38,\"relation\":\"eq\"},\"max_score\":null,\"hits\":[]},\"aggregations\":{\"3\":{\"doc_count_error_upper_bound\":0,\"sum_other_doc_count\":0,\"buckets\":[{\"key\":\"error_entry\",\"doc_count\":34},{\"key\":\"error_patch\",\"doc_count\":4}]}}};
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
Object obj = getDeepFieldValue(jsonObject, "aggregations.3.buckets.[key=error_entry].doc_count");
System.out.println(obj.toString());
}
public Object getDeepFieldValue(JSONObject jsonObject, String jsonPath) {
String[] split = jsonPath.split("\\.");
Object currentObject = jsonObject;
for (String item : split) {
if (currentObject instanceof JSONObject) {
JSONObject temp = (JSONObject) currentObject;
if (temp.containsKey(item)) {
currentObject = temp.get(item);
} else {
return null;
}
} else if (currentObject instanceof JSONArray) {
JSONArray temps = (JSONArray) currentObject;
String[] kv = item.replace("[", "").replace("]", "").split("=");
boolean exist = false;
for (Object obj : temps) {
if (obj instanceof JSONObject) {
JSONObject json = (JSONObject) obj;
if (kv.length == 2 && json.containsKey(kv[0]) && String.valueOf(json.get(kv[0])).equals(kv[1])) {
currentObject = json;
exist = true;
break;
}
}
}
if (!exist) {
return null;
}
} else {
return null;
}
}
return currentObject;
}