且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中使用JsonPath从JSON获得价值?

更新时间:2023-01-18 08:12:59

您可以单独使用JsonPath库实现您的目标.这是一个示例:

You can achieve your goal with JsonPath library on its own. Here is an example:

    String jsonString = "{ \"list\": [ { \"name\": \"foo1\"}, { \"name\": \"foo2\"} ]}";
    DocumentContext docCtx = JsonPath.parse(jsonString);
    JsonPath jsonPath = JsonPath.compile("$.list[?(@.name == \"foo1\")]");
    JSONArray val1=docCtx.read(jsonPath);
    System.out.println(val1);

此代码将打印出来:

[{"name":"foo1"}]

所需的maven依赖项:

Required maven dependency:

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

json-path还将自动拉出json-smart JAR:

json-path will also automatically pull json-smart JAR:

<dependency>
    <groupId>net.minidev</groupId>
    <artifactId>json-smart</artifactId>
    <version>2.2.1</version>
</dependency>