Enterprise Java

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:

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.

OperationTargetPatchResult
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.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button