Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách lấy giá trị của một khóa sử dụng interface JsonPointer trong Java


JSONPointer là một tiêu chuẩn định nghĩa cú pháp chuỗi để truy cập một giá trị khóa cụ thể trong tài liệu JSON. Một thể hiện của JSONPointer có thể được tạo bằng cách gọi phương thức factory tĩnh createPointer() trên lớp Json. Trong JSONPointer, mọi cú pháp chuỗi đều được tiền tố bằng “/”. Chúng ta có thể lấy giá trị của một khóa bằng cách gọi phương thức getValue() trên đối tượng JsonPointer.

File JSON

Cách lấy giá trị của một khóa sử dụng interface JsonPointer trong Java

Ví dụ

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()); // in 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()); // in phone numbers       }       JsonPointer jsonPointer3 = Json.createPointer("/phoneNumbers/1");       JsonObject jsonObject1 = (JsonObject)jsonPointer3.getValue(jsonStructure);       System.out.println("Home: " + jsonObject1.toString()); // in home phone number       JsonPointer jsonPointer4 = Json.createPointer("");       JsonObject jsonObject2 = (JsonObject)jsonPointer4.getValue(jsonStructure);       System.out.println("JSON:\n" + jsonObject2.toString()); // in JSON structure       jsonReader.close();    } }

Kết quả

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"}]}