多层嵌套JSON找出指定key对应值
背景: 需要从一个不确定的JSON中找出一个指定key对应的值,返回一个Map<String,Object>。 注意点: 因为不确定有几层json嵌套,需要递归解析,只到解析成一个对象值 或者找到了指定key。
具体代码实现举例: 本次只写了Int类型,其他类型类似 我全部写在测试类中,可直接运行测试:
package xxx.xxx.xxx(自己类路径); import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.*; public class TestJson { public static void main(String[] args) { //json格式的String字段 String json = "{"josnOne":{"number":"101","Demo2":{"label":"test1","key":"customerCode1"},"projectName":"测试manage"},"JsonTwo":{"Demo2":{"label":"张淑娜","key":"10007319622","number1":"102"},"A":"A","Phone":"13466666666"}}"; //String 转为Json JSONObject jsonObject = JSONObject.parseObject(json); //要查找的key,例如number、number1 List<String> list = Arrays.asList("number","number1"); //查询到的值 Map<key,key对应的值> Map<String, Object> result = new HashMap<>(); ParsingJson(jsonObject,list,result); System.out.println(result); } /** * 获取指定key对应value值 * @param content json对象 * @param conditionKey 要查找的key * @param result 输出map */ public static void ParsingJson(JSONObject content,List<String> conditionKey ,Map<String, Object> result) { Set<String> keySet = content.keySet(); conditionKey.forEach(conkey -> { keySet.forEach(key -> { Object contentKey = content.get(key); //如果是一个对象 if (contentKey instanceof JSONObject) { JSONObject jsonObject = (JSONObject) contentKey; //判断是否存在key Integer keyValue = jsonObject.getInteger(conkey); if(Objects.nonNull(keyValue)){ //赋值map result.put(conkey,keyValue); //递归 }else { ParsingJson(jsonObject,Arrays.asList(conkey),result); } //如果是一个值 } else if (contentKey instanceof JSONArray) { JSONArray jsonArray = (JSONArray) contentKey; //判断当前是否找到key if(key.equals(conkey)){ Integer keyValue = Integer.valueOf(jsonArray.toJSONString()); //赋值map result.put(conkey,keyValue); } } }); }); } }
看一下运行结果