JSON循环遍历解析

使用递归方式遍历JSON,解析JSON用的是:net.sf.json, alibaba.fastjson测试可用

 1  @Test
 2     public void test() {
 3         String json = "{}";
 4         test2((Map) JSONObject.fromObject(json));
 5     }
 6 
 7     private void test1(Map.Entry<String, Object> entry) {
 8         if (entry.getValue() instanceof JSONArray) {
 9             System.out.println("key=" + entry.getKey());
10             List<Map<String, Object>> list = (List<Map<String, Object>>) entry.getValue();
11             for (Map<String, Object> map : list) {
12                 test2(map);
13             }
14         } else if (entry.getValue() instanceof JSONObject) {
15             System.out.println("key=" + entry.getKey());
16             Map jsonMap = (Map) JSONObject.fromObject(entry.getValue());
17             test2(jsonMap);
18         } else {
19             System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
20         }
21     }
22 
23     private void test2(Map map) {
24         Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
25         while (it.hasNext()) {
26             Map.Entry<String, Object> en = it.next();
27             test1(en);
28         }
29     }

 

posted @ 2017-12-28 09:19  从余  阅读(8176)  评论(0编辑  收藏  举报