Enterprise Java

Get to Know JSON 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 Patch

JSON Patch expresses a sequence of operations to apply against a target JSON document. The operations are formatted in JSON-Pointer notation and can perform: add, copy, move, remove, replace and test operations.

The JsonPatchBuilder interface is the gateway into this API and is created from the static method createPatchBuilder() in the Json class. A JSON Pointer expression is passed to one of the operation methods and applied to a JSON document.

The Replace Operation

The replace operation is performed by the replace() method and passing it the location of the element to replace expressed as a JSON Pointer expression and the replacement value.

{
"title": "Java EE: Only What's New",
"author": "Alex Theedom",
"chapters": [
  "Chapter 1: Java EE 8 What’s New Overview",
  "Chapter 2: Java API for JSON Binding 1.0 (JSR 367)",
  "Chapter 3: Java EE Security API 1.0 (JSR 375)"
],
"released": true,
"pages": 300,
"sourceCode": {
  "repositoryName": "Java-EE-8-Only-Whats-New",
  "url": "github.com/readlearncode/"
},
"otherBooks": [
  {
    "title": "Professional Java EE Design Patterns",
    "length": 350
  }
]
}

JsonObject jsonObject = ... create JSONObject from JSON document ...;

In the code snippet below and given the JSON document above, the value of the first element of the chapters array, represented by the JSON pointer expression /chapters/0, is replaced by the value Chapter 1: Introduction.

JsonPatchBuilder builder = Json.createPatchBuilder();

JsonPatch jsonPatch = builder
     .replace("/chapters/0", "Chapter 1: Introduction")
     .build();

JsonObject newJsonObject = jsonPatch.apply(jsonObject);

The apply() method returns an instance of the JsonStructure class.

The Add and Remove Operations

A key feature of JSON Patch is the capability to chain multiple operations together and applied them sequentially to the result of the previous patch result. If an exception is thrown during the patch operation it ceases operation and no changes are made to the original JSON document.

The code example below shows how to add and remove elements from a JSON document.

JsonObject newJsonObject = Json.createPatchBuilder()
      .add("/chapters/3", "Chapter 4: Servlets 4.0")
      .remove("/released")
      .build()
      .apply(jsonObject);

The add() method takes a JSON Pointer expression which identifies the element where to insert new data. The second element is the new data to insert.

To remove an element pass the JSON Pointer of the element to remove to the remove() method.

The Move and Copy Operations

The move operation requires two JSON Pointer expressions:

  • one for the element to move and
  • one for the target location to where the value will be moved.

The target location must already exist and follows the same logic as the add operation in the sense that it displaces the element at the specified location with the element to move. All elements are effectively shifted down one position.

The copy operation replaces an element’s value with the value of another element. This operations also requires two JSON pointer expressions: one for the source value and one for the target’s location.

The code snippet below chains three operations together: two move operations and a copy operation.

JsonObject newJsonObject = Json.createPatchBuilder()
      .move("/chapters/0", "/chapters/2")
      .move("/chapters/2", "/chapters/1")
      .copy("/otherBooks/0/length", "/pages")
      .build()
      .apply(jsonObject);

The move operation moves the value located in the third position of the chapters array to the first position, then moves the element in the second position to the third position. The copy operation copies the value of pages key to the length key of the first element in the otherBooks array.

The Test Operation

The test operation determines if the specified value is set in the JSON document. If the test fails the patch operations ceases, otherwise it goes ahead and completes the remaining operations.

In the code snippet, the element /pages is tested. If its value is 300 the copy operation continues, otherwise a JsonException is thrown.

JsonObject newJsonObject = Json.createPatchBuilder()
      .test("/pages", 300)
      .copy("/otherBooks/0/length", "/pages") // destination, source
      .build()
      .apply(jsonObject);

Conclusion

Well, that’s it for the second 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 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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button