问题

json串是一种非常常用的数据格式,如果json串中含有多层嵌套,并且有数组存在应该如何定位到我们具体想要的某个元素呢?

解决

1、引用相关依赖

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

2、使用.get。万能.get,只需要注意返回格式即可。

//JSON串
JSONObject oneData = (JSONObject) data.get(0);
//JSON数组
JSONArray honor = (JSONArray) oneData.get("honor");
//字符串
String summary = (String) oneData.get("summary");

举例

JSON串

{
	"code": "500",
	"time": "123456",
	"msg": {
		"school": {
			"total": 2,
			"data": [
                {
				    "startTime": "123",
				    "summary": "小学阶段",
				    "grade": "3",
				    "honor": [
				    	"先进个人",
			    		"优秀学生"
			    	],
				    "gdesc": "三年级八班"
			    }, 
                {
				    "startTime": "456",
				    "summary": "初中阶段",
				    "grade": "2",
				    "honor": [
				    	"体育委员"
			    	],
				    "gdesc": "初2年级二班"
			    }
            ]

		}
	}
}

 

示例代码

//res即为上图字符串
        JSONObject totalObject = JSON.parseObject(res);
        String code = (String) totalObject.get("code");
        log.debug("显示1");
        log.debug( String.valueOf(code));
        JSONObject msg = (JSONObject) totalObject.get("msg");
        log.debug("显示2");
        log.debug(String.valueOf(msg));
        JSONObject school = (JSONObject) msg.get("school");
        log.debug("显示3");
        log.debug(String.valueOf(school));
        JSONArray data = (JSONArray) school.get("data");
        JSONObject oneData = (JSONObject) data.get(0);
        log.debug("显示4");
        log.debug(String.valueOf(oneData));
        JSONArray honor = (JSONArray) oneData.get("honor");
        log.debug("显示5");
        log.debug(String.valueOf(honor));
        String summary = (String) oneData.get("summary");
        log.debug("显示6");
        log.debug(summary);

结果显示

- 显示1
 - 500
 - 显示2
 - {"school":{"total":2,"data":[{"summary":"小学阶段","gdesc":"三年级八班","grade":"3","honor":["先进个人","优秀学生"],"startTime":"123"},{"summary":"初中阶段","gdesc":"初2年级二班","grade":"2","honor":["体育委员"],"startTime":"456"}]}}
 - 显示3
 - {"total":2,"data":[{"summary":"小学阶段","gdesc":"三年级八班","grade":"3","honor":["先进个人","优秀学生"],"startTime":"123"},{"summary":"初中阶段","gdesc":"初2年级二班","grade":"2","honor":["体育委员"],"startTime":"456"}]}
 - 显示4
 - {"summary":"小学阶段","gdesc":"三年级八班","grade":"3","honor":["先进个人","优秀学生"],"startTime":"123"}
 - 显示5
 - ["先进个人","优秀学生"]
 - 显示6
 - 小学阶段