Processing JSON using JSON Pointer

The following example reads the JSON representation of the employee object from the emp.json file and uses the javax.json.JsonPointer API to reference the firstName value inside the JSON document and modify its contents.

First, create an instance of JsonObject using JsonReader. Then, define the JsonPointer for the firstName reference. Using JsonPointer, access or modify the value defined against firstName:

public class JSR374JsonPointerExample {

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();

//Step-2: Create the JSON Pointer passing the reference location
JsonPointer pointer = Json.createPointer("/firstName");

//Step-3: Fetch the firstName from target object using the pointer
JsonValue value = pointer.getValue(jsonObject);

logger.log(Level.INFO, "Fetched First Name:{0}", value.toString());

//Step-4: Alter the first name to different value
JsonValue replaceFirstName = Json.createValue("Mike");
jsonObject = pointer.add(jsonObject, replaceFirstName);

//Step-5: Fetch the modified firstName from target object using the pointer
value = pointer.getValue(jsonObject);

logger.log(Level.INFO, "Modified First Name:{0}", value.toString());
}
}

The preceding program reads the emp.json file and prints the input and modified employee first name, as shown ahead:

Output of the Program:
Fetched First Name:"John"
Modified First Name:"Mike"
..................Content has been hidden....................

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