How to get the values of a key using the JsonPointer interface in Java?



The JSONPointer is a standard that defines a string syntax that can be used to access a particular key value in the JSON document. An instance of JSONPointer can be created by calling the static factory method createPointer() on the Json class. In the JSONPointer, every string syntax is prefixed with “/”. We can get the value of a key by calling the getValue() method on the JsonPointer object.

JSON file

Example

import javax.json.*; import java.io.*; public class JsonPointerTest {    public static void main(String[] args) throws Exception {       JsonReader jsonReader = Json.createReader(new FileReader("simple.json"));       JsonStructure jsonStructure = jsonReader.read();       JsonPointer jsonPointer1 = Json.createPointer("/firstName");       JsonString jsonString = (JsonString)jsonPointer1.getValue(jsonStructure);       System.out.println("First Name: " + jsonString.getString()); // prints first name       JsonPointer jsonPointer2 = Json.createPointer("/phoneNumbers");       JsonArray array = (JsonArray)jsonPointer2.getValue(jsonStructure);       System.out.println("Phone Numbers:");       for(JsonValue value : array) {          JsonObject objValue = (JsonObject)value;          System.out.println(objValue.toString()); // prints phone numbers       }       JsonPointer jsonPointer3 = Json.createPointer("/phoneNumbers/1");       JsonObject jsonObject1 = (JsonObject)jsonPointer3.getValue(jsonStructure);       System.out.println("Home: " + jsonObject1.toString()); // prints home phone number       JsonPointer jsonPointer4 = Json.createPointer("");       JsonObject jsonObject2 = (JsonObject)jsonPointer4.getValue(jsonStructure);       System.out.println("JSON:\n" + jsonObject2.toString()); // prints JSON structure       jsonReader.close();    } }

Output

First Name: Raja Phone Numbers: {"Mobile":"9959984000"} {"Home":"0403758000"} Home: {"Home":"0403758000"} JSON: {"firstName":"Raja","lastName":"Ramesh","age":30,"streetAddress":"Madhapur","city":"Hyderabad","state":"Telangana","phoneNumbers":[{"Mobile":"9959984000"},{"Home":"0403758000"}]}
Updated on: 2020-07-07T11:58:26+05:30

791 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements