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

How do I get value from JSON using JsonPath in Java?

我想使用 JsonPath.Could 从 JSON 对象中获取值 任何人请向我推荐我需要的合适的 jar,因为据我所知,我正在为我的 jar 获取此异常我正在使用 jsonpath .

package jsonPg;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import com.jayway.jsonpath.JsonPath;

public class ReadJsonPath {

    static String file = "D:\AutomationSample\Sample_Json.txt";

    public static void main(String[] args) throws JSONException, IOException {
        JsonReadFile jsonReadFile=new JsonReadFile();
        JSONObject jsonObj=jsonReadFile.parseJSONFile(file);
        String jsonObject=jsonObj.toString();
        String json="";
        System.out.println(jsonObject);
//      Object val = JsonPath.read(jsonObject,"");
        String val1=JsonPath.read(jsonObject," $.payload[*].supplierDataMap[*].COMPANYDETAILS.customFieldList[*].DISPLAYGSID   .value");
        System.out.println(val1);

     }

 }

这是我编写的代码,下面是运行时抛出的异常

    Exception in thread "main" java.lang.NoSuchFieldError: FACTORY_SIMPLE
     at com.jayway.jsonpath.spi.impl.JsonSmartJsonProvider.<init>(JsonSmartJsonProvider.java:38)
at com.jayway.jsonpath.spi.impl.JsonSmartJsonProvider.<init>(JsonSmartJsonProvider.java:41)
at com.jayway.jsonpath.spi.JsonProviderFactory.<clinit>  (JsonProviderFactory.java:24)
at    com.jayway.jsonpath.Configuration.defaultConfiguration(Configuration.java:62)
at com.jayway.jsonpath.internal.JsonReader.<init>(JsonReader.java:26)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:462)
at jsonPg.ReadJsonPath.main(ReadJsonPath.java:27)`

如有任何帮助,我们将不胜感激。 提前致谢。

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

    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 依赖项:

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

json-path 也会自动拉取 json-smart JAR:

<dependency>
    <groupId>net.minidev</groupId>
    <artifactId>json-smart</artifactId>
    <version>2.2.1</version>
</dependency>
   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);