代码大概是这样的,比较暴力:
@Test
public void testJsonPathAndType() {
String str = "{\n" +
" \"data\":{\n" +
" \"age\":180,\n" +
" \"username\":\"tom\",\n" +
" \"address\":{\n" +
" \"province\":\"上海市\",\n" +
" \"city\":\"上海市\"\n" +
" },\n" +
" \"family\":[\n" +
" {\n" +
" \"brother\":\"jack\"\n" +
" },\n" +
" {\n" +
" \"sister\":\"lucy\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
String key = "brother";
if (!StringUtils.contains(str,key)){
System.out.println(StrUtil.format("不包含key【{}】",key));
}
List<String> list = new ArrayList<>();
getPath(key,JSONObject.parseObject(str,Map.class),list);
System.out.println(list.stream().collect(Collectors.joining(".")));
}
public Boolean getPath(String key, Map<String,Object> map, List<String> list){
Boolean[] result = new Boolean[]{Boolean.FALSE};
if (map.containsKey(key)){
list.add(0,key);
return Boolean.TRUE;
}
map.forEach((k,v)->{
if (v instanceof Map || v instanceof JSONObject){
try {
Map<String,Object> temMap = JSONObject.parseObject(JSONObject.toJSONString(v),Map.class);
if(getPath(key,temMap,list)){
list.add(0,k);
result[0] = Boolean.TRUE;
return;
}
}catch (Exception e) {
System.out.println(StrUtil.format("{}转换Map异常{},执行下一个key值遍历",
JSONObject.toJSONString(v),e.getMessage()));
}
}
if (v instanceof List){
((List) v).forEach(e -> {
if (! (e instanceof Map || e instanceof JSONObject)){
return;
}
if (getPath(key,JSONObject.parseObject(JSONObject.toJSONString(e),Map.class),list)){
list.add(0,k);
result[0] = Boolean.TRUE;
return;
}
});
}
});
return result[0];
}
至于类型判断你就根据list去根map里面获取之后用instanceof 去判断吧 |