所需要的包
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!!!
---------------长按二维码关注程序媛小姐姐公众号有更多彩蛋哦---------------