采用递归的方式,遍历JSON中所有的KEY。 JSON格式如下: {"username":"tom","age":18,"address":[{"province":"上海市"},{"city":"上海市"},{"disrtict":"静安区"}]} 处理后,得到的结果如下: address|province|city|disrtict|username|age packageai.advance.until; importcom.alibaba.fastjson.JSONObject; importcom.alibaba.fastjson.JSONArray; public classfastJsonDiff { /** * 递归读取所有的key * * @paramjsonObject */ public staticStringBuffer getAllKey(JSONObject jsonObject) { StringBuffer stringBuffer = newStringBuffer(); Iterator<String> keys = jsonObject.keySet().iterator();//jsonObject.keys(); while(keys.hasNext()) { String key =keys.next(); stringBuffer.append(key.toString()).append("|"); if (jsonObject.get(key) instanceofJSONObject) { JSONObject innerObject =(JSONObject) jsonObject.get(key); stringBuffer.append(getAllKey(innerObject)); } else if (jsonObject.get(key) instanceofJSONArray) { JSONArray innerObject =(JSONArray) jsonObject.get(key); stringBuffer.append(getAllKey(innerObject)); } } returnstringBuffer; } public staticStringBuffer getAllKey(JSONArray json1) { StringBuffer stringBuffer = newStringBuffer(); if (json1 != null) { Iterator i1 =json1.iterator(); while(i1.hasNext()) { Object key =i1.next(); if (key instanceofJSONObject) { JSONObject innerObject =(JSONObject) key; stringBuffer.append(getAllKey(innerObject)); } else if (key instanceofJSONArray) { JSONArray innerObject =(JSONArray) key; stringBuffer.append(getAllKey(innerObject)); }else{ } } } returnstringBuffer; } private final static String st1 = "{"username":"tom","age":18,"address":[{"province":"上海市"},{"city":"上海市"},{"disrtict":"静安区"}]}"; private final static String st2 = "{username:"tom",age:18}"; public static voidmain(String[] args) { System.out.println(st1); JSONObject jsonObject1 =JSONObject.parseObject(st1); StringBuffer stb =getAllKey(jsonObject1); System.err.println(stb); } }
获取JSON中所有的KEY
免责声明:文章转载自《获取JSON中所有的KEY》仅用于学习参考。如对内容有疑问,请及时联系本站处理。
上篇自己动手添加一个OpenWrt开机启动脚本mysql--统计每个用户的累计访问次数下篇
宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=