解析一个含有json对象、数组格式的数据

废话不多说,直接贴出要解析的json数据:

{
	"requestId": "61701564-ab07-4039-b751-52548c3e315c",
	"success": true,
	"data":{
		"total":2,
		"detail": [{
			"id": 1,
			"name": "小明",
			"age": "15"
		}, {
			"id": 2,
			"name": "小刚",
			"age": "18",
		}]
	}
}

 看似简单(数据量少),其实也不简单(结构略复杂,包含了json对象与json数组)。

解析一个含有json对象、数组格式的数据

如:上图中红框中的数据格式就是json对象,而其中蓝框中的数据格式又是json数组。

现在将其中所有json信息解析出来,具体参考下方代码:

package com.zhicall.ladder.esb.service;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.bag.SynchronizedSortedBag;

public class JsonParserTest {

    public static void main(String[] args) {
        String json = "{\n" +
                "\t\"requestId\": \"61701564-ab07-4039-b751-52548c3e315c\",\n" +
                "\t\"success\": true,\n" +
                "\t\"data\":{\n" +
                "\t\t\"total\":2,\n" +
                "\t\t\"detail\": [{\n" +
                "\t\t\t\"id\": 1,\n" +
                "\t\t\t\"name\": \"小明\",\n" +
                "\t\t\t\"age\": \"15\"\n" +
                "\t\t}, {\n" +
                "\t\t\t\"id\": 2,\n" +
                "\t\t\t\"name\": \"小刚\",\n" +
                "\t\t\t\"age\": \"18\",\n" +
                "\t\t}]\n" +
                "\t}\n" +
                "}";
        parseJsonInfo(json);
    }

    public static void parseJsonInfo(String json) {
        System.out.println("====开始解析====");
        JSONObject jsonObject = JSONObject.fromObject(json);
        String requestId = jsonObject.getString("requestId");
        System.out.println("\"requestId\" = " + requestId);
        String success = jsonObject.getString("success");
        System.out.println("\"success\" = " + success);
        String total = jsonObject.getJSONObject("data").getString("total");
        System.out.println("\"total\" = " + total);
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("detail");
        for(int i =0;i<jsonArray.size();i++){
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            String id = jsonObject1.getString("id");
            System.out.println("\"id\" = " + id);
            String name = jsonObject1.getString("name");
            System.out.println("\"name\" = " + name);
            String age = jsonObject1.getString("age");
            System.out.println("\"age\" = " + age);
        }
        System.out.println("====解析结束====");
    }
}

输出结果:

====开始解析====
"requestId" = 61701564-ab07-4039-b751-52548c3e315c
"success" = true
"total" = 2
"id" = 1
"name" = 小明
"age" = 15
"id" = 2
"name" = 小刚
"age" = 18
====解析结束====

注意以上导包都是net.sf.json,不要搞错了。

getJSONObject()为获取json对象数据;

getJSONArray()为获取json数组数据;

获取指定格式数据后,getString()获取指定key对应的value值即可。