JsonPath 入门

我们任然遵循学习新知识的基本方法,先编写一个简单的“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 应该非常熟悉,如下图:

JsonPath 入门

运行示例,输出如下:

author: Nigel Rees
author: Evelyn Waugh
author: Herman Melville
author: J. R. R. Tolkien
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号