News Ticker

Get to Know JSON Merge Patch: JSON-P 1.1 Overview Series

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.

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. If you want to know more about JSON Processing and Java EE then my new book Java EE 8: Only What’s New is the book for you, and it’s available for a special launch price of only $9.95.

Follow this link to get your copy, today.

That’s all for now.

Related Articles

Leave a Reply

%d bloggers like this: