Processing JSON using JSON Patch

The following example reads the JSON representation of the employee object from the emp.json file and uses the javax.json.JsonPatch API to add the gender value and remove hiredate inside the JSON document:

  1. Read the target JSON document using JsonReader
  2. Instantiate PatchBuilder
  3. Use PatchBuilder to add gender data
  4. Use PatchBuilder to remove hiredate
  5. Construct and apply patch operations on the target JSON document

The implementation of the previous steps is demonstrated in the following program:

public class JSR374JsonPatchExample {

private static final Logger logger = Logger.getLogger(JSR374JsonPointerExample.class.getName());

public static void main(String[] args) throws IOException {
logger.setLevel(Level.INFO);

//Step-1 Read the Target JSON Document using JSR 353 API as mentioned in the //previous sections
String jsonFileName = "/emp.json";
InputStream inputStream = JSR374JsonPointerExample.class.getResourceAsStream(jsonFileName);
Reader reader = new InputStreamReader(inputStream, "UTF-8");

JsonReader jsonReader = Json.createReader(reader);
JsonObject jsonObject = (JsonObject) jsonReader.read();

logger.log(Level.INFO, "Input Employee:{0}", jsonObject.toString());

//Step-2: Instantiate the Patch Builder to include patch operations
JsonPatchBuilder patchBuilder = Json.createPatchBuilder();

//Step-3: Add gender data to Employee data
patchBuilder.add("/gender", "Male");
//Step-4:Remove the hireDate from Employee data
patchBuilder.remove("/hireDate");

//Step-5: Construct and apply the patch operations on the
//target object
JsonPatch patch = patchBuilder.build();
jsonObject = patch.apply(jsonObject);


logger.log(Level.INFO, "Output Employee:{0}", jsonObject.toString());
}

The preceding program reads the emp.json file and prints the input and patched JsonObject, as shown ahead:

Output of the Program:
Input Employee:{"employeeId":100,"firstName":"John","lastName":"Chen","email":"[email protected]","hireDate":"2008-10-16"}
Output Employee:{"employeeId":100,"firstName":"John","lastName":"Chen","email":"[email protected]","gender":"Male"}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.254