What is JSON-PATCH, is it useful ?
HTTP PATCH operation is use to apply partial updates, in this article we are going to explore specific type of PATCH standard which is primarily use to apply on JSON documents, it classifies such documents with media type “application/json-patch+json", technically it is associated with RFC-6902 standard.
The request structure is as follows :
[
{ "op": "add", "path": "/path", "value": ["value"] }
]
There can be multiple operations for the op field i.e add, remove, replace, copy etc, the path value represents a nested object in the JSON document, and the value property contains the value need to be updated on the given path.
Examples :
Following are some series of examples for patch operations
To replace element property
[
{ "op": "replace", "path": "/foo/", "value": "qux" }
]
To add element in any given position in array
[
{ "op": "add", "path": "/foo/1", "value": "qux" }
]
To add element at the end of array
[
{ "op": "add", "path": "/foo/-", "value": "qux" }
]
Removing element, obviously it didn’t need value property
[
{ "op": "remove", "path": "/foo/1" }
]
Testing if patch is applicable on document
[
{ "op": "test", "path": "/baz", "value": "qux" }
]
This standard can be implemented in many languages there are numerous builtin libraries available, for this article we will limit our scope for java implementation.
Following steps should be taken to implement JSON PATCH in Spring Boot application :
Add a dependency for either Maven or Gradle :
With Gradle
dependencies {
compile(group: "com.github.java-json-tools", name: "json-patch", version: "version");
}
With Maven
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-patch</artifactId>
<version>version</version>
</dependency>
Use the following piece of code to apply patch
For more information please walk through this official document