Get to Know JSON Merge Patch: JSON-P 1.1 Overview Series
Java EE 8 includes an update to the JSON Processing API and brings it up to date with the latest IEFT standards for JSON. They are:
- JSON Pointer RFC 6901
- JSON Patch RFC 6902
- JSON Merge Patch RFC 7396
I will cover these topics in this mini-series.
Getting Started
To get started with JSON-P you will need the following dependencies from the Maven central repository.
<dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.1</version> </dependency>
JSON-Merge Patch
JSON Merge patch is a JSON document that describes a set of changes to be made to a target JSON document. This table shows three of the operations available.
Operation | Target | Patch | Result |
Replace | {"color":"blue"} | {"color":"red"} | {"color":"red"} |
Add | {"color":"blue"} | {"color":"red"} | {"color":"blue", "color":"red"} |
Remove | {"color":"blue"} | {"color": null} | {} |
The static method createMergePatch() on the Json class provides an instance of the type JsonMergePatch to which you pass the patch. The apply() method of the resulting JsonMergePatch instance is passed the target JSON and the patch is applied. The code below shows how to perform the replace operation from the table.
Json.createMergePatch(Json.createValue("{\"colour\":\"blue\"}")) .apply(Json.createValue("{\"colour\":\"red\"}"));
Merge Diff
The merge diff operation generates a JSON Merge Patch from a source and target JsonValue which when applied to the source would result in the target.
JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue target = Json.createValue("{\"colour\":\"red\"}"); JsonMergePatch jsonMergePatch = Json.createMergeDiff(source, target); JsonValue jsonValue = jsonMergePatch.apply(source);
Conclusion
Well, that’s it for the third article in this mini-series about JSON Processing’s new features.
That’s all for now.
Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: Get to Know JSON Merge Patch: JSON-P 1.1 Overview Series Opinions expressed by Java Code Geeks contributors are their own. |