1. 程式人生 > >java遍歷json字串取值

java遍歷json字串取值

所需要的包

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

一、json字串結構如下:

{
  "code": "OK",
  "message": "",
  "data": {
    "departmentId": 320000,
    "name": "江蘇省",
    "children": [
      {
        "departmentId": 320200,
        "name": "無錫市",
        "children": [
          {
            "departmentId": 320211,
            "name": "濱湖區",
            "children": []
          }
        ]
      },
      {
        "departmentId": 320500,
        "name": "蘇州市",
        "children": []
      }
    ]
  }
}

很明顯是list裡面包含list

二、java遍歷json取值這裡只是取出 departmentId,程式碼如下:

  // 先將字串或者json資料轉換為JSONObject
        JSONObject jsonObj = JSONObject.fromObject(treeDto);
        JSONArray family = jsonObj.getJSONArray("children");//獲取到data下children的集合
        if (family != null) {
            for (Object obj : family) {
                JSONObject jo = (JSONObject) obj;
                Long status = jo.getLong("departmentId"); //取出data下children中的departmentId
                JSONArray childrenx = jo.getJSONArray("children");//獲取到data下children集合中的children集合
                if (childrenx != null) {
                    for (Object objx : childrenx) {
                        JSONObject jox = (JSONObject) objx;
                        Long statusx = jox.getLong("departmentId"); //取出data下children中的children中的departmentId
                        list.add(statusx);
                    }
                }
                list.add(status);
            }
        }

 

最後list裡面就是取出了所有的departmentId的值;

注意:list中並不包含‘江蘇省’的departmentId!!!