Json檔案轉Map(三)之獲取巢狀Map值
阿新 • • 發佈:2018-12-20
說明
在上一章節的部落格中,我們已經學習瞭如何解析巢狀的Json,將獲取巢狀Json的節點。那麼在這一章節中,如何通過以下的節點格式去取值。
- index8=results>index>index7>
- index7=results>index>
- index=results>
- index2=results>
- results=null
分析及實現
既然我們已經解析了JSON檔案,並且轉化了Map,而且還拿到了巢狀Json的節點,現在無非就是遍歷Map,然後重新取值,這個邏輯應該不難。程式碼如下:
/** * 根據json報文和結點獲取相應的值 * @param map 已經解析過的Json * @param listNode 要獲取的欄位在json中的節點路徑(用">"分割) * @return */ public static List<Map<String,Object>> gainJsonMapValue(Map jsonMap,String stringNode){ List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>(); String[] nodeArray = stringNode.split(">"); for (int i = 0; i < nodeArray.length; i++) { if (jsonMap.get(nodeArray[i]) instanceof List) { if (i < nodeArray.length&& null != jsonMap.get(nodeArray[i]) && "" != jsonMap.get(nodeArray[i])) { Map<String,Object> mapList = jsonMap; if (((List<Map<String,Object>>)mapList.get(nodeArray[i])).size() > 0) { Map map = new HashMap(); map.put(nodeArray[i], ((List<Map<String,Object>>)mapList.get(nodeArray[i]))); resultList.add(map); } } break; } else{ if (i < nodeArray.length - 1 && null != jsonMap.get(nodeArray[i]) && "" != jsonMap.get(nodeArray[i])) { jsonMap = (Map) jsonMap.get(nodeArray[i]); }else{ Map<String,Object> resultMap = new HashMap<String,Object>(); resultMap.put(nodeArray[i],jsonMap.get(nodeArray[i])+"");//nodeArray resultList.add(resultMap); } } } // System.out.println("#####"+resultList); return resultList; }
小結
這篇部落格只是簡單的說明一下如何去取已經解析出來的Map節點。在下一篇部落格中,筆者將會把所有程式碼都分享出來。