Overview
- Java and Kotlin are very powerful statically typed languages, but sometimes we face situations where we need to handle dynamically changing objects according to requirements. Examples include Map, List, and JSON strings of type String. Reading, adding, and modifying this data can be quite cumbersome. Using
Jayway JsonPath
, data can be controlled in a very elegant and easy manner based on the Path.
build.gradle.kts
- Add the following content to the build.gradle.kts file at the project root.
dependencies {
implementation("com.jayway.jsonpath:json-path:2.9.0")
}
Initializing JsonPath Object
- It's time to initialize JsonPath from the original source.
val inputJsonPath = JsonPath.parse(input)
JsonPath.parse()
can take a String
type containing a JSON string as an argument. (If it's not a valid JSON string, com.jayway.jsonpath.InvalidJsonException exception is thrown.) It can also take dynamically stored data in Map<String, Any>
, List<String>
types as arguments.
Querying Data with JsonPath
- Use
.read()
to easily query data from complex paths.
inputJsonPath.read("$['foo']['bar']") as List<Map<String, Any>>
inputJsonPath.read("$['foo']['bar'].length()") as Int
JsonPath Data Addition/Modification
- Use
.put()
to add/modify data and set()
for data modification.
inputJsonPath.put("$['foo']", "bar", "foobar")
inputJsonPath.set("$['foo']['bar']", "foobar")
.put()
ignores if the Path does not exist. It creates a new Key if it does not exist, and overwrites the existing value if it does.
.set()
ignores if the Path does not exist. (A com.jayway.jsonpath.PathNotFoundException exception occurs if the parent Path does not exist.) That is, it overwrites the existing value only if the Key exists.
Acquiring Result Data with JsonPath
- Use
.json()
, .jsonString()
to obtain the result data.
val outputMap = inputJsonPath.json() as Map<String, Any>
val outputJsonString = inputJsonPath.jsonString()
- For the final result,
.json()
allows type conversion to Map<String, Any>
or List<String>
.
- For the final result,
.jsonString()
returns a String
type containing a JSON string.
References and Further Reading