0

I need to parse the json in example1 using jsonpath similar to the below example2. But could not find the path since the type of the json is string. Please suggest me some possible ways to parse the json string to modify the value for colourCode dynamically.

Example1:

{
    "payload": "{\"carBrand\":{\"model\":{\"colourCode\":2147483647}}}"
}

Example2:

{phone:{phoneType:"iPhone","cat":"11"}}

Jsonpath:

$.phone.phoneType

This will return "iPhone"

1 Answer 1

1

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

String jsonString ="{\"phone\":{\"phoneType\":\"iPhone\",\"cat\":\"11\"}}";
String jsonExp = "$.phone.phoneType";
DocumentContext docCtx = JsonPath.parse(jsonString);
JsonPath jsonPath = JsonPath.compile(jsonExp);
String val1=docCtx.read(jsonPath);
System.out.println(val1); // print iPhone

Maven Dependency

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

You can refer to the documentation below for various other api's you can use.

https://github.com/json-path/JsonPath/blob/master/README.md
https://www.baeldung.com/guide-to-jayway-jsonpath
Sign up to request clarification or add additional context in comments.

3 Comments

There is no JsonNode class in com.jayway.jsonpath. I can see only ValueNode.JsonNode. Is there anything I have to do?
@user3879701 Modified the answer and tested it locally as well. It should work for you
@user3879701 Actually that was a mistake, you don't need JsonNode. You can achieve your use case using normal JsonPath only. I have updated the code, please let me know if you face any issues. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.