如何使用 Java 中的 JsonPointer 接口获取键值?
JSONPointer 是一个标准,它定义了用于访问 JSON 文档中特定键值的字符串语法。通过调用Json 类上的静态工厂方法createPointer()可以创建一个JSONPointer 实例。在JSONPointer 中,每个字符串语法都以“/”开头。我们可以通过调用JsonPointer 对象上的getValue()方法来获取键的值。
JSON 文件
示例
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(); } }
输出
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"}]}
广告