使用fastjson获取json串中的所有键值对
程序员文章站
2022-06-12 20:16:00
...
获取json中的所有键值对 不含jsonarry哈 有需要自己修改
具体如下
package com.zj.test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.util.*; public class Test_json { public static void main(String[] args){ String s = "{\"A\":{\"B\":{\"C\":1,\"D\":2}},\"E\":3}"; JSONObject jsonObject = JSONObject.parseObject(s); Map param = new HashMap(); for (Map.Entry entry : jsonObject.entrySet()) { String object = jsonObject.getString(String.valueOf(entry.getKey())); param.put(entry.getKey(),object); if(isJsonObject(object)){ JSONObject son = JSONObject.parseObject(JSON.parseObject(object, String.class)); getAllKey(son,param); } } System.out.println("=======>"+param); } public static Boolean isJsonObject(String jsonString){ try{ JSONObject.parseObject(JSON.parseObject(jsonString, String.class)); return true; }catch (Exception e){ return false; } } public static void getAllKey(JSONObject jsonObject,Map param){ for (Map.Entry entry : jsonObject.entrySet()) { String string = jsonObject.getString(String.valueOf(entry.getKey())); param.put(entry.getKey(),string); if(isJsonObject(string)){ JSONObject son = JSONObject.parseObject(JSON.parseObject(string, String.class)); getAllKey(son,param); } } } }
查询结果为
=======>{A={"B":{"C":1,"D":2}}, B={"C":1,"D":2}, C=1, D=2, E=3}