Simple JsonPatch Example

JsonPatch is a format for storing a sequence of operations that has to be applied on the target json structure. The following operations can be stored in JsonPath and operated
on json structure
1) add
2) remove
3) replace
4) move
5) copy
6) test

Java jdk provides api for creating JsonPatch. The post explains how to use it with an example. For the example we will use the below data

jsondata.txt


{
    "firstName": "Duke",
    "lastName": "Java",
    "age": 18,
    "streetAddress": "100 Internet Dr",
    "city": "JavaTown",
    "state": "JA",
    "postalCode": "12345",
    "phoneNumbers": [
        { "Mobile": "111-111-1111" },
        { "Home": "222-222-2222" }
    ]
}

Main Code


1  import java.io.FileReader;
2  
3  import javax.json.Json;
4  import javax.json.JsonPatch;
5  import javax.json.JsonPatchBuilder;
6  import javax.json.JsonReader;
7  import javax.json.JsonStructure;
8  
9  public class Example6 {
10  public static void main(String[] args) throws Exception {
11         JsonPatchBuilder jsonPatchBuilder = Json.createPatchBuilder();
12         JsonPatch jsonPatch = jsonPatchBuilder.add("/sex", "M").remove("/age").build();
13         
14         JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
15         JsonStructure jsonStructure1 = reader.read();
16         JsonStructure jsonStructure2 = jsonPatch.apply(jsonStructure1);
17         System.out.println(jsonStructure2);
18         reader.close();
19     }
20 }

Explanation

In the example, we store two operations (i.e., add and remove) in the variable jsonPatch. This is done with the help of JsonPatchBuilder. Refer to line 11 and 12.

Once the JsonPatch is created we apply the patch on the target structure using the apply method as shown at line 16, where jsonPatch contains two operations in JsonPatch format
and jsonStructure1 contains data from the file jsondata.txt.

The result of apply method is another JsonStructure instance which is stored in variable jsonStructure2 and printed at line 17.

Output

{“firstName”:”Duke”,”lastName”:”Java”,”streetAddress”:”100 Internet Dr”,”city”:”JavaTown”,”state”:”JA”,”postalCode”:”12345″,”phoneNumbers”:[{“Mobile”:”111-111-1111″},
{“Home”:”222-222-2222″}],”sex”:”M”}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s