我们任然遵循学习新知识的基本方法,先编写一个简单的“Hello World”程序。
在 maven 的 pom.xml 文件中添加如下依赖:
<dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.9.0</version> </dependency>
使用 JsonPath.read() 静态方法,提取指定 JSON 字符串中所有书籍(book)的作者信息,代码如下:
package com.hxstrive.json_path; import com.jayway.jsonpath.JsonPath; import java.util.List; /** * Jayway JsonPath 入门示例 * @author hxstrive.com */ public class Demo { public static void main(String[] args) { String 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" + "}"; // 获取所有书籍的作者 List<String> authors = JsonPath.read(json, "$.store.book[*].author"); for(String author : authors) { System.out.println("author: " + author); } } }
注意,上述示例中,“$.store.book[*].author”是一个 JsonPath 字符串,其中,$ 表示当前整个 JSON 字符串,* 是一个通配符,$.store.book[*] 表示获取所有的书籍信息。
如果读者曾经使用过 ApiFox 工具的变量提取,那么对 JsonPath 应该非常熟悉,如下图:
运行示例,输出如下:
author: Nigel Rees author: Evelyn Waugh author: Herman Melville author: J. R. R. Tolkien