Importance of the JsonPatch interface in Java?


The JsonPatch interface is a format for storing a sequence of operations that can be applied to the target JSON structure. There are few operations like add, remove, replace, copy, move and test can be stored in JsonPath and operated on JSON structure. The JsonPatchBuilder interface can be used for constructing a JSON patch using the Json.createPatchBuilder().

JSON file


Example

import java.io.*;
import javax.json.Json;
import javax.json.JsonPatch;
import javax.json.JsonPatchBuilder;
import javax.json.JsonReader;
import javax.json.JsonStructure;
public class JsonPatchTest {
   public static void main(String[] args) throws Exception {
      JsonPatchBuilder jsonPatchBuilder = Json.createPatchBuilder();
      JsonPatch jsonPatch = jsonPatchBuilder.add("/postalCode", "500072").remove("/age").build();
      JsonReader reader = Json.createReader(new FileReader("simple.json"));
      JsonStructure jsonStructure1 = reader.read();
      JsonStructure jsonStructure2 = jsonPatch.apply(jsonStructure1);
      System.out.println(jsonStructure2);
      reader.close();
   }
}

Output

{"firstName":"Raja","lastName":"Ramesh","streetAddress":"Madhapur","city":"Hyderabad","state":"Telangana","phoneNumbers":[{"Mobile":"9959984000"},{"Home":"7702144400"}],"postalCode":"500072"}

Updated on: 07-Jul-2020

478 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements