1. 程式人生 > >使用jsonPath解析多層json資料

使用jsonPath解析多層json資料

    第一步,匯入jsonPath所需jar包(json-path-0.8.1.jar,json-smart-1.1.1.jar,commons-lang-2.6.jar),下載地址:https://download.csdn.net/download/cling_snail/10531694。

    第二步,使用jsonPath解析資料,下面是jsonPath的簡單語法和示例:

    json資料:

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

以上是一些簡單的jsonpath語法示例。

        下面是我專案中使用的jsonpath,因為我的專案是整合高德地圖,通過高德api介面傳送地址,獲取到高德返回的地址經緯度,所以需要解析高德返回的json資料。

    mian方法中呼叫介面:

         //傳送 POST 請求
        String sr=HttpRequest.sendPost("https://restapi.amap.com/v3/geocode/geo", "address=天津市河東區大王莊六緯路與十四徑路交口&output=JSON&key=自己在高德上申請的web端key值");
        //獲取高德地圖伺服器返回的json格式資料
        System.out.println("狀態:"+json2String(sr,"$..status"));    //獲取到json中所有的status值
        System.out.println("地址:"+json2String(sr,"$..formatted_address"));    //獲取到json中所有的formatted_address值

        System.out.println("經緯度:"+json2String(sr,"$..location"));    //獲取到json中所有的location值

    其中的sr為json格式的資料:{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"天津市河東區六緯路/十四徑路","province":"天津市","citycode":"022","city":"天津市","district":"河東區","township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"120102","street":[],"number":[],"location":"117.228002,39.116834","level":"道路交叉路口"}]}

 解析結果:           

        好了,此時就能解析出json資料了,是不是很簡單,假如不使用jsonPath,就要通過一層一層的遍歷獲取json資料中的值,增加了程式碼的複雜度和工作量。