Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to get the value from the JSON object using JsonPath.Could anyone please suggest me the appropriate jars which i would need because as per my knowledge i am getting this exception for the jars i am using for 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);

     }

 }

here is the code which i have written and below is the exception which is thrown at runtime

    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)`

Any kind of help would be appreciated . Thanks in advance .

like image 487
Tanmay Matondkar Avatar asked Oct 17 '22 13:10

Tanmay Matondkar


1 Answers

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);

This code will print out:

[{"name":"foo1"}]

Required maven dependency:

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

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

<dependency>
    <groupId>net.minidev</groupId>
    <artifactId>json-smart</artifactId>
    <version>2.2.1</version>
</dependency>
like image 174
RZet Avatar answered Oct 21 '22 02:10

RZet