天天看點

JSONPath小試

最近在某論壇看到一個關于JSONPath的例子,講這個東西乃對JSON處理的神器,今日碰到周五,就來試試幾把。
           

一、JSON字元串

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": ,
        "isbn": "0-553-21311-3"
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 
    }
  }
}
           

二、基本腳本

public class JSONPathTest {

    public static void main(String[] args) throws Exception {
        InputStream is = JSONPathTest.class.getResourceAsStream("data.json");
        JSONObject jsonObject = JsonPath.read(is, "$");
        //使用JSONPath讀取指定值
        Map<String, Object> jsonObj = (Map<String, Object>)JsonPath.read(jsonObject, "$.store.book[0]");
        //讀取内容
        System.out.println("category: " + jsonObj.get("category"));
        System.out.println("author: " + jsonObj.get("author"));
        System.out.println("title: " + jsonObj.get("title"));
        System.out.println("price: " + jsonObj.get("price"));

        System.out.println("========================");
        List<String> authors = (List<String>)JsonPath.read(jsonObject, "$.store.book[*].author");
        for (String author : authors) {
            System.out.println(author);
        }
    }
}
           

三、使用總結

1. 使用JSONPath.reader方法讀取inputStream的時候,隻能讀取一次,再次讀取的時候會導緻異常;

2. JSONPath跟Xpath算是難兄難弟吧,JSONPath算是模拟XPath的一個翻版吧。

四、參考連結

1. JSONPath-簡單入門

2. JsonPath的使用