JsonPath是一种简单的方法来提取给定JSON文档的部分内容。 JsonPath有许多编程语言,如Javascript,Python和PHP,Java。

JsonPath提供的json解析非常强大,它提供了类似正则表达式的语法,基本上可以满足所有你想要获得的json内容。下面我把官网介绍的每个表达式用代码实现,可以更直观的知道该怎么用它。

GitHub:https://github.com/json-path/JsonPath

以下是从GitHub中用我蹩脚的英格利希,翻译过来的,将就着看吧,推荐去管网上面阅读。


JsonPath可在Central Maven存储库中找到。 Maven用户将其添加到您的POM。

<dependency><groupId>com.jayway.jsonpath</groupId><artifactId>json-path</artifactId><version>2.2.0</version>
</dependency>

如果您需要帮助,请在Stack Overflow中提问。 标记问题'jsonpath'和'java'。

JsonPath表达式总是以与XPath表达式结合使用XML文档相同的方式引用JSON结构。

JsonPath中的“根成员对象”始终称为$,无论是对象还是数组。

JsonPath表达式可以使用点表示法

$.store.book [0].title

或括号表示法

$['store']['book'][0]['title']

操作符

操作 说明
$ 查询根元素。这将启动所有路径表达式。
@ 当前节点由过滤谓词处理。
* 通配符,必要时可用任何地方的名称或数字。
.. 深层扫描。 必要时在任何地方可以使用名称。
.<name> 点,表示子节点
['<name>' (, '<name>')] 括号表示子项
[<number> (, <number>)] 数组索引或索引
[start:end] 数组切片操作
[?(<expression>)] 过滤表达式。 表达式必须求值为一个布尔值。

函数

函数可以在路径的尾部调用,函数的输出是路径表达式的输出,该函数的输出是由函数本身所决定的。

函数 描述 输出
min() 提供数字数组的最小值 Double
max() 提供数字数组的最大值 Double
avg() 提供数字数组的平均值 Double
stddev() 提供数字数组的标准偏差值 Double
length() 提供数组的长度 Integer

过滤器运算符

过滤器是用于筛选数组的逻辑表达式。一个典型的过滤器将是[?(@.age > 18)],其中@表示正在处理的当前项目。 可以使用逻辑运算符&&和||创建更复杂的过滤器。 字符串文字必须用单引号或双引号括起来([?(@.color == 'blue')] 或者 [?(@.color == "blue")]).

操作符 描述
== left等于right(注意1不等于'1')
!= 不等于
< 小于
<= 小于等于
> 大于
>= 大于等于
=~ 匹配正则表达式[?(@.name =~ /foo.*?/i)]
in 左边存在于右边 [?(@.size in ['S', 'M'])]
nin 左边不存在于右边
size (数组或字符串)长度
empty (数组或字符串)为空

Java操作示例

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 (点击链接测试) 结果
$.store.book[*].author 获取json中store下book下的所有author值
$..author 获取所有json中所有author的值
$.store.* 所有的东西,书籍和自行车
$.store..price 获取json中store下所有price的值
$..book[2] 获取json中book数组的第3个值
$..book[-2] 倒数的第二本书
$..book[0,1] 前两本书
$..book[:2] 从索引0(包括)到索引2(排除)的所有图书
$..book[1:2] 从索引1(包括)到索引2(排除)的所有图书
$..book[-2:] 获取json中book数组的最后两个值
$..book[2:] 获取json中book数组的第3个到最后一个的区间值
$..book[?(@.isbn)] 获取json中book数组中包含isbn的所有值
$.store.book[?(@.price < 10)] 获取json中book数组中price<10的所有值
$..book[?(@.price <= $['expensive'])] 获取json中book数组中price<=expensive的所有值
$..book[?(@.author =~ /.*REES/i)] 获取json中book数组中的作者以REES结尾的所有值(REES不区分大小写)
$..* 逐层列出json中的所有值,层级由外到内
$..book.length() 获取json中book数组的长度

阅读文档

使用JsonPath的最简单的最直接的方法是通过静态读取API。

Java

String json = "...";
List<String> authors = JsonPath.read(json, "$.store.book[*].author");

如果你只想读取一次,那么上面的代码就可以了

如果你还想读取其他路径,现在上面不是很好的方法,因为他每次获取都需要再解析整个文档。所以,我们可以先解析整个文档,再选择调用路径。

Java

String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);String author0 = JsonPath.read(document, "$.store.book[0].author");
String author1 = JsonPath.read(document, "$.store.book[1].author");

JsonPath还提供流畅的API。 这也是最灵活的一个。

Java

String json = "...";
ReadContext ctx = JsonPath.parse(json);List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");List<Map<String, Object>> expensiveBooks = JsonPath.using(configuration).parse(json).read("$.store.book[?(@.price > 10)]", List.class);

何时返回

当在java中使用JsonPath时,重要的是要知道你在结果中期望什么类型。 JsonPath将自动尝试将结果转换为调用者预期的类型。

Java

// 抛出 java.lang.ClassCastException 异常
List<String> list = JsonPath.parse(json).read("$.store.book[0].author")// 正常
String author = JsonPath.parse(json).read("$.store.book[0].author")

当评估路径时,你需要理解路径确定的概念。路径是不确定的,它包含

  • .. :深层扫描操作

  • ?(<expression>) :表达式

  • [<number>, <number> (, <number>)] :多个数组索引

不确定的路径总是返回一个列表(由当前的JsonProvider表示)。

默认情况下,MappingProvider SPI提供了一个简单的对象映射器。 这允许您指定所需的返回类型,MappingProvider将尝试执行映射。 在下面的示例中,演示了Long和Date之间的映射。

Java

String json = "{\"date_as_long\" : 1411455611975}";
Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);

如果您将JsonPath配置为使用JacksonMappingProvider或GsonMappingProvider,您甚至可以将JsonPath输出直接映射到POJO中。

Java

Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);

要获取完整的泛型类型信息,请使用TypeRef。

Java

TypeRef<List<String>> typeRef = new TypeRef<List<String>>(){};
List<String> titles = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[*].title", typeRef);

谓词

在JsonPath中创建过滤器谓词有三种不同的方法。

内联谓词

内联谓词是路径中定义的谓词。

Java

List<Map<String, Object>> books =  JsonPath.parse(json).read("$.store.book[?(@.price < 10)]");

你可以使用 && 和 || 结合多个谓词 [?(@.price < 10 && @.category == 'fiction')] , [?(@.category == 'reference' || @.price > 10)].

你也可以使用!否定一个谓词 [?(!(@.price < 10 && @.category == 'fiction'))].

过滤谓词

谓词可以使用Filter API构建,如下所示:

Java

import static com.jayway.jsonpath.JsonPath.parse;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
...
...Filter cheapFictionFilter = filter(where("category").is("fiction").and("price").lte(10D)
);List<Map<String, Object>> books = parse(json).read("$.store.book[?]", cheapFictionFilter);

注意占位符? 为路径中的过滤器。 当提供多个过滤器时,它们按照占位符数量与提供的过滤器数量相匹配的顺序应用。 您可以在一个过滤器操作[?,?]中指定多个谓词占位符,这两个谓词都必须匹配。

过滤器也可以与“OR”和“AND”

Java

Filter fooOrBar = filter(where("foo").exists(true)).or(where("bar").exists(true)
);Filter fooAndBar = filter(where("foo").exists(true)).and(where("bar").exists(true)
);

自定义

第三个选择是实现你自己的谓词

Java

Predicate booksWithISBN = new Predicate() {@Overridepublic boolean apply(PredicateContext ctx) {return ctx.item(Map.class).containsKey("isbn");}
};List<Map<String, Object>> books = reader.read("$.store.book[?].isbn", List.class, booksWithISBN);

Path vs Value

在Goessner实现中,JsonPath可以返回Path或Value。 值是默认值,上面所有示例返回。 如果你想让我们查询的元素的路径可以通过选项来实现。

Java

Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build();List<String> pathList = using(conf).parse(json).read("$..author");assertThat(pathList).containsExactly("$['store']['book'][0]['author']", "$['store']['book'][1]['author']","$['store']['book'][2]['author']", "$['store']['book'][3]['author']");

调整配置

选项创建配置时,有几个可以改变默认行为的选项标志。

DEFAULT_PATH_LEAF_TO_NULL

此选项使JsonPath对于缺少的叶子返回null。 考虑下面的json

[{"name" : "john","gender" : "male"},{"name" : "ben"}
]

Java

Configuration conf = Configuration.defaultConfiguration();// 正常
String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
// 异常 PathNotFoundException thrown
String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);// 正常
String gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
// 正常 (返回 null)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");

ALWAYS_RETURN_LIST

此选项配置JsonPath返回列表

Java

Configuration conf = Configuration.defaultConfiguration();// 正常
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
// 异常 PathNotFoundException thrown
List<String> genders1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");

SUPPRESS_EXCEPTIONS

该选项确保不会从路径评估传播异常。 遵循这些简单的规则:

  • 如果选项ALWAYS_RETURN_LIST存在,将返回一个空列表

  • 如果选项ALWAYS_RETURN_LIST不存在返回null

JsonProvider SPI

JsonPath is shipped with three different JsonProviders:

  • JsonSmartJsonProvider (default)

  • JacksonJsonProvider

  • JacksonJsonNodeJsonProvider

  • GsonJsonProvider

  • JsonOrgJsonProvider

更改配置默认值只能在应用程序初始化时完成。 强烈不建议在运行时进行更改,尤其是在多线程应用程序中。

Java

Configuration.setDefaults(new Configuration.Defaults() {private final JsonProvider jsonProvider = new JacksonJsonProvider();private final MappingProvider mappingProvider = new JacksonMappingProvider();@Overridepublic JsonProvider jsonProvider() {return jsonProvider;}@Overridepublic MappingProvider mappingProvider() {return mappingProvider;}@Overridepublic Set<Option> options() {return EnumSet.noneOf(Option.class);}
});

请注意,JacksonJsonProvider需要com.fasterxml.jackson.core:jackson-databind:2.4.5,GsonJsonProvider需要在您的类路径上使用com.google.code.gson:gson:2.3.1。

Cache SPI

在JsonPath 2.1.0中,引入了一种新的Cache SPI。 这允许API消费者以适合其需求的方式配置路径缓存。 缓存必须在首次访问之前配置,或者抛出JsonPathException。 JsonPath附带两个缓存实现

  • com.jayway.jsonpath.spi.cache.LRUCache(默认,线程安全)

  • com.jayway.jsonpath.spi.cache.NOOPCache(无缓存)

如果要实现自己的缓存,API很简单。

Java

CacheProvider.setCache(new Cache() {//Not thread safe simple cacheprivate Map<String, JsonPath> map = new HashMap<String, JsonPath>();@Overridepublic JsonPath get(String key) {return map.get(key);}@Overridepublic void put(String key, JsonPath jsonPath) {map.put(key, jsonPath);}
});

Java操作示例源码

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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"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}

java

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import com.jayway.jsonpath.JsonPath;public class TestJsonPath {public static void main(String[] args) {String sjson = readtxt();print("--------------------------------------getJsonValue--------------------------------------");getJsonValue(sjson);}private static String readtxt() {StringBuilder sb = new StringBuilder();try {FileReader fr = new FileReader("D:/books.txt");BufferedReader bfd = new BufferedReader(fr);String s = "";while((s=bfd.readLine())!=null) {sb.append(s);}} catch (Exception e) {e.printStackTrace();}System.out.println(sb.toString());return sb.toString();}private static void getJsonValue(String json) {//The authors of all books:获取json中store下book下的所有author值List<String> authors1 = JsonPath.read(json, "$.store.book[*].author");//All authors:获取所有json中所有author的值List<String> authors2 = JsonPath.read(json, "$..author");//All things, both books and bicycles //authors3返回的是net.minidev.json.JSONArray:获取json中store下的所有value值,不包含key,如key有两个,book和bicycleList<Object> authors3 = JsonPath.read(json, "$.store.*");//The price of everything:获取json中store下所有price的值List<Object> authors4 = JsonPath.read(json, "$.store..price");//The third book:获取json中book数组的第3个值List<Object> authors5 = JsonPath.read(json, "$..book[2]");//The first two books:获取json中book数组的第1和第2两个个值List<Object> authors6 = JsonPath.read(json, "$..book[0,1]");//All books from index 0 (inclusive) until index 2 (exclusive):获取json中book数组的前两个区间值List<Object> authors7 = JsonPath.read(json, "$..book[:2]");//All books from index 1 (inclusive) until index 2 (exclusive):获取json中book数组的第2个值List<Object> authors8 = JsonPath.read(json, "$..book[1:2]");//Last two books:获取json中book数组的最后两个值List<Object> authors9 = JsonPath.read(json, "$..book[-2:]");//Book number two from tail:获取json中book数组的第3个到最后一个的区间值List<Object> authors10 = JsonPath.read(json, "$..book[2:]");//All books with an ISBN number:获取json中book数组中包含isbn的所有值List<Object> authors11 = JsonPath.read(json, "$..book[?(@.isbn)]");//All books in store cheaper than 10:获取json中book数组中price<10的所有值List<Object> authors12 = JsonPath.read(json, "$.store.book[?(@.price < 10)]");//All books in store that are not "expensive":获取json中book数组中price<=expensive的所有值List<Object> authors13 = JsonPath.read(json, "$..book[?(@.price <= $['expensive'])]");//All books matching regex (ignore case):获取json中book数组中的作者以REES结尾的所有值(REES不区分大小写)List<Object> authors14 = JsonPath.read(json, "$..book[?(@.author =~ /.*REES/i)]");//Give me every thing:逐层列出json中的所有值,层级由外到内List<Object> authors15 = JsonPath.read(json, "$..*");//The number of books:获取json中book数组的长度List<Object> authors16 = JsonPath.read(json, "$..book.length()");print("**********authors1**********");print(authors1);print("**********authors2**********");print(authors2);print("**********authors3**********");printOb(authors3);print("**********authors4**********");printOb(authors4);print("**********authors5**********");printOb(authors5);print("**********authors6**********");printOb(authors6);print("**********authors7**********");printOb(authors7);print("**********authors8**********");printOb(authors8);print("**********authors9**********");printOb(authors9);print("**********authors10**********");printOb(authors10);print("**********authors11**********");printOb(authors11);print("**********authors12**********");printOb(authors12);print("**********authors13**********");printOb(authors13);print("**********authors14**********");printOb(authors14);print("**********authors15**********");printOb(authors15);print("**********authors16**********");printOb(authors16);}private static void print(List<String> list) {for(Iterator<String> it = list.iterator();it.hasNext();) {System.out.println(it.next());}}private static void printOb(List<Object> list) {for(Iterator<Object> it = list.iterator();it.hasNext();) {System.out.println(it.next());}}private static void print(String s) {System.out.println("\n"+s);}}输出
{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"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}--------------------------------------getJsonValue--------------------------------------
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/apache/logging/log4j/log4j-slf4j-impl/2.0.2/log4j-slf4j-impl-2.0.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/slf4j/slf4j-log4j12/1.7.10/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.**********authors1**********
Nigel Rees
Evelyn Waugh
Herman Melville
X-rapido
J. R. R. Tolkien**********authors2**********
Nigel Rees
Evelyn Waugh
Herman Melville
X-rapido
J. R. R. Tolkien**********authors3**********
[{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
{color=red, price=19.95}**********authors4**********
8.95
12.99
8.99
32.68
22.99
19.95**********authors5**********
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}**********authors6**********
{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}**********authors7**********
{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}**********authors8**********
{category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}**********authors9**********
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}**********authors10**********
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}**********authors11**********
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}**********authors12**********
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}**********authors13**********
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}**********authors14**********
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}**********authors15**********
{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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"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}}
10
[{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
{color=red, price=19.95}
{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=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
reference
Nigel Rees
Sayings of the Century
8.95
fiction
Evelyn Waugh
Sword of Honour
12.99
fiction
Herman Melville
Moby Dick
0-553-21311-3
8.99
JavaWeb
X-rapido
Top-link
0-553-211231-3
32.68
fiction
J. R. R. Tolkien
The Lord of the Rings
0-395-19395-8
22.99
red
19.95**********authors16**********
5

示例2

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;public class TestJsonPath3 {public static void main(String[] args) {String sjson = readtxt();print("-----------------------getJsonValue0-----------------------");getJsonValue0(sjson);print("-----------------------getJsonValue1-----------------------");getJsonValue1(sjson);print("-----------------------getJsonValue2-----------------------");getJsonValue2(sjson);print("-----------------------getJsonValue3-----------------------");getJsonValue3(sjson);print("-----------------------getJsonValue4-----------------------");getJsonValue4(sjson);}private static String readtxt() {StringBuilder sb = new StringBuilder();try {FileReader fr = new FileReader("D:/books.txt");BufferedReader bfd = new BufferedReader(fr);String s = "";while((s=bfd.readLine())!=null) {sb.append(s);}} catch (Exception e) {e.printStackTrace();}System.out.println(sb.toString());return sb.toString();}/*** 读取json的一种写法,得到匹配表达式的所有值* */private static void getJsonValue0(String json) {List<String> authors = JsonPath.read(json, "$.store.book[*].author");print(authors);}/*** 读取JSON得到某个具体值(推荐使用这种方法,一次解析多次调用)* */private static void getJsonValue1(String json) {Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);String author0 = JsonPath.read(document, "$.store.book[0].author");String author1 = JsonPath.read(document, "$.store.book[1].author");print(author0);print(author1);}/*** 读取json的一种写法* */private static void getJsonValue2(String json) {ReadContext ctx = JsonPath.parse(json);// 获取json中book数组中包含isbn的作者List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");// 获取json中book数组中价格大于10的对象List<Map<String, Object>> expensiveBooks = JsonPath.using(Configuration.defaultConfiguration()).parse(json).read("$.store.book[?(@.price > 10)]", List.class);print(authorsOfBooksWithISBN);print("********Map********");printListMap(expensiveBooks);}/*** 读取JSON得到的值是一个String,所以不能用List存储 * */private static void getJsonValue3(String json) {//Will throw an java.lang.ClassCastException    //List<String> list = JsonPath.parse(json).read("$.store.book[0].author");//由于会抛异常,暂时注释上面一行,要用的话,应使用下面的格式String author = JsonPath.parse(json).read("$.store.book[0].author");print(author);}/*** 读取json的一种写法,支持逻辑表达式,&&和||*/private static void getJsonValue4(String json) {List<Map<String, Object>> books1 =  JsonPath.parse(json).read("$.store.book[?(@.price < 10 && @.category == 'fiction')]");List<Map<String, Object>> books2 =  JsonPath.parse(json).read("$.store.book[?(@.category == 'reference' || @.price > 10)]");print("********books1********");printListMap(books1);print("********books2********");printListMap(books2);}private static void print(List<String> list) {for(Iterator<String> it = list.iterator();it.hasNext();) {System.out.println(it.next());}}private static void printListMap(List<Map<String, Object>> list) {for(Iterator<Map<String, Object>> it = list.iterator();it.hasNext();) {Map<String, Object> map = it.next();for(Iterator iterator =map.entrySet().iterator();iterator.hasNext();) {System.out.println(iterator.next());}}}private static void print(String s) {System.out.println("\n"+s);}}输出
{"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":"JavaWeb","author":"X-rapido","title":"Top-link","isbn":"0-553-211231-3","price":32.68},{"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}-----------------------getJsonValue0-----------------------
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/apache/logging/log4j/log4j-slf4j-impl/2.0.2/log4j-slf4j-impl-2.0.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/workSpaces/SupportPackge/MavenRepository/org/slf4j/slf4j-log4j12/1.7.10/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
Nigel Rees
Evelyn Waugh
Herman Melville
X-rapido
J. R. R. Tolkien-----------------------getJsonValue1-----------------------Nigel ReesEvelyn Waugh-----------------------getJsonValue2-----------------------
Herman Melville
X-rapido
J. R. R. Tolkien********Map********
category=fiction
author=Evelyn Waugh
title=Sword of Honour
price=12.99
category=JavaWeb
author=X-rapido
title=Top-link
isbn=0-553-211231-3
price=32.68
category=fiction
author=J. R. R. Tolkien
title=The Lord of the Rings
isbn=0-395-19395-8
price=22.99-----------------------getJsonValue3-----------------------Nigel Rees-----------------------getJsonValue4-----------------------********books1********
category=fiction
author=Herman Melville
title=Moby Dick
isbn=0-553-21311-3
price=8.99********books2********
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=JavaWeb
author=X-rapido
title=Top-link
isbn=0-553-211231-3
price=32.68
category=fiction
author=J. R. R. Tolkien
title=The Lord of the Rings
isbn=0-395-19395-8
price=22.99

过滤器示例

Java

public static void main(String[] args) {String json = readtxt();Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);// 过滤器链(查找包含isbn并category中有fiction或JavaWeb的值)Filter filter = Filter.filter(Criteria.where("isbn").exists(true).and("category").in("fiction", "JavaWeb"));List<Object> books = JsonPath.read(document, "$.store.book[?]", filter);printOb(books);System.out.println("\n----------------------------------------------\n");// 自定义过滤器Filter mapFilter = new Filter() {@Overridepublic boolean apply(PredicateContext context) {Map<String, Object> map = context.item(Map.class);    if (map.containsKey("isbn")) {return true;}return false;}};List<Object> books2 = JsonPath.read(document, "$.store.book[?]", mapFilter);printOb(books2);}输出
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}----------------------------------------------{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=JavaWeb, author=X-rapido, title=Top-link, isbn=0-553-211231-3, price=32.68}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}

由此可见,使用过滤器,或者使用上述的表达式,都是可以达到理想的效果

示例中的books2中,注意到context.item(Map.class); 这句话

这句中的Map.class是根据预定的结果类型定义的,如果返回的是String类型值,那就改为String.class

我的示例只简单判断了一下isbn属性,可以根据实际情况进行变更条件

使用 JSONPath 解析 JSON 完整内容详解相关推荐

  1. java json path_Java使用JSONPath解析JSON完整内容详解

    JsonPath是一种简单的方法来提取给定JSON文档的部分内容. JsonPath有许多编程语言,如Javascript,Python和PHP,Java. JsonPath提供的json解析非常强大 ...

  2. java读取json文件内容_java读取json文件内容详解

    之前给大家介绍了一下java读取txt文件内容,下面要给大家介绍的就是java读取json文件内容,一起来了解一下吧. 1.java读取json文件 下面是具体的思路: 首先是获取文件-获取文件内容- ...

  3. Linux安装Docker并配置Docker镜像加速,daemon.json完整配置详解

    文章目录

  4. Sentry For Vue 完整接入详解(2021 Sentry v21.8.x)前方高能预警!三万字,慎入!

    内容源于:https://docs.sentry.io/platforms/javascript/guides/vue/ 系列 1 分钟快速使用 Docker 上手最新版 Sentry-CLI - 创 ...

  5. viper4android io错误,golang常用库之配置文件解析库-viper使用详解

    一.viper简介 viper 配置管理解析库,是由大神 Steve Francia 开发,他在google领导着 golang 的产品开发,他也是 gohugo.io 的创始人之一,命令行解析库 c ...

  6. STM32CubeMX GCC工程Makefile内容详解

    STM32CubeMX GCC工程Makefile内容详解 基础介绍 因为项目原因,需要对编译系统进行一些比较复杂的使用,但是我对于编译系统这一块并不是非常精通了解,所以需要进行一下学习.正巧,众所周 ...

  7. python3d动态图-Python图像处理之gif动态图的解析与合成操作详解

    本文实例讲述了Python图像处理之gif动态图的解析与合成操作.分享给大家供大家参考,具体如下: gif动态图是在现在已经司空见惯,朋友圈里也经常是一言不合就斗图.这里,就介绍下如何使用python ...

  8. C#深入解析Json格式内容

    继上一篇<浅谈C#手动解析Json格式内容>我又来分析加入了一些功能让 这个解析类更实用 本章节最会开放我最终制作成功的Anonymous.Json.dll这个解析库 需要的拿走~ 功能继 ...

  9. python request.post 字典参数以json_Python requests.post方法中data与json参数区别详解

    在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json. data与json既可以是str类型,也可以是dict类型. 区别: 1.不管json是 ...

最新文章

  1. SAP零售:补货 Vs 多步骤补货
  2. 250相当于什么显卡_2K(4K)144hz显示器需要什么显卡来带? 本文将给你答案。
  3. JAVA enum实现简单状态机功能
  4. shiro教程(2)- shiro介绍
  5. 【❗JS奇技淫巧❗】JavaScript:截取DataURL中的base64字符串
  6. 6大设计模式(4):接口隔离原则
  7. php二分法 冒泡 快速排序,PHP 常见算法【冒泡排序, 快速排序, 插入排序, 取舍排序, 二分法查找, .】...
  8. Vue.js 服务器端渲染指南
  9. Ubuntu18.04中配置QT5.11开发环境
  10. GPS之Ublox方案设计
  11. Digester基本用法
  12. 尺度空间-多尺度特征空间
  13. 中国“中产阶级”只赚钱不读书 被指精神荒芜
  14. [4G5G专题-70]:物理层 - 4G LTE 下行物理控制格式指示信道PCFICH与物理下行控制信道PDCCH
  15. MV* 模式梳理与理解(还原真实的 MV* 模式)
  16. jav中什么是组织java程序_Javs ^运算符在Java中做什么?
  17. Docker之使用maven插件【Dockerfile方式】构建并推送镜像到私有仓库
  18. 使用nid修改dbname和dbid
  19. NSSCTF-SWPU新生赛
  20. Android adb 安装 apk无法安装错误排查

热门文章

  1. 20230111英语学习
  2. 苏大强投资被骗欲跳楼,原本他可以逃过此劫~~
  3. SqlServer:sql添加外键约束
  4. 七十二般变化解得了三灾?
  5. Python学习笔记(35)~异位词
  6. oracle常见sql面试题,ORACLEPLSQL超经典面试题
  7. 2022-2028年全球与中国塑料奶瓶行业市场需求预测分析
  8. 【软件架构】运用RUP 4+1视图软件架构设计(逻辑视图、实现视图、进程视图、物理视图和用例视图)
  9. Intellij IDEA集成PHP
  10. Java 位运算理解 Java中的位移运算整理 Java右移n位 Java左移n位