1. 程式人生 > 實用技巧 >遞迴獲取jsonObject的所有value

遞迴獲取jsonObject的所有value

 //遞迴獲取jsonObject的所有value
 private StringBuffer mStringBuffer = new StringBuffer();
 public  String getAllContentFromJson(Object cObject) {

        if(cObject instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) cObject;
            for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
                Object o 
= entry.getValue(); if(o instanceof Integer){ log.info("key:" + entry.getKey() + ",value:" + entry.getValue()); mStringBuffer.append(" "+entry.getValue()); }else if(o instanceof Double){ log.info("key:" + entry.getKey() + ",value:" + entry.getValue()); mStringBuffer.append(
" "+entry.getValue()); }else if(o instanceof Float){ log.info("key:" + entry.getKey() + ",value:" + entry.getValue()); mStringBuffer.append(" "+entry.getValue()); }else if(o instanceof Byte){ log.info("key:" + entry.getKey() + ",value:" + entry.getValue()); mStringBuffer.append(
" "+entry.getValue()); }else if(o instanceof Long){ log.info("key:" + entry.getKey() + ",value:" + entry.getValue()); mStringBuffer.append(" "+entry.getValue()); }else if(o instanceof String) { Object object = null; try{ object=JSONObject.parseObject((String)o); getAllContentFromJson(object); }catch (Exception e){ log.info("key:" + entry.getKey() + ",value:" + entry.getValue()); mStringBuffer.append(" "+entry.getValue()); } } else { getAllContentFromJson(o); } } } if(cObject instanceof JSONArray) { JSONArray jsonArray = (JSONArray) cObject; for(int i = 0; i < jsonArray.size(); i ++) { getAllContentFromJson(jsonArray.get(i)); } } return mStringBuffer.toString(); }