JSONPath小试

最近在某论坛看到一个关于JSONPath的例子,讲这个东西乃对JSON处理的神器,今日碰到周五,就来试试几把。

一、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,
        "isbn": "0-553-21311-3"
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

二、基本脚本

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 jsonObj = (Map)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 authors = (List)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的使用

你可能感兴趣的:(Java基础)