- Java EE 8 and Angular
- Prashant Padmanabhan
- 361字
- 2021-07-02 19:22:32
JSON Processing API
JSON-P can be considered as having two core APIs:

Let's look at what the parsing API looks like when trying to parse the previous sample document. First we need to obtain a parser using the Json class. This class is a factory class for creating JSON processing objects:
JsonParser parser = Json.createParser(Main.class.getResourceAsStream("/sample.json"));
Next, we use the returned JsonParser object to loop over all the entries using the hasNext() method, similar to an iterator, and in turn invoke the next() method, which emits a JsonParser.Event instance. This instance will hold the current JSON entry which can be a key or value:
while (parser.hasNext()) {
JsonParser.Event e = parser.next();
System.out.print(e.name());
switch (e) {
case KEY_NAME:
System.out.print(" - " + parser.getString());
break;
case VALUE_STRING:
System.out.print(" - " + parser.getString());
break;
case VALUE_NUMBER:
System.out.print(" - " + parser.getString());
}
System.out.println();
}
Using the preceding loop, we will be able to parse and examine each entry as we go through the entire document.
Apart from creating parsers using the Json class, we can also obtain a JsonObjectBuilder instance which is used to create JSON object models from scratch. A one line demo is shown as follows, and creates a JsonObject:
JsonObject json = Json.createObjectBuilder().add("name", "Feature ABC").build();
More advanced usage is possible by nesting calls to the add(...) method, which we will look at later on. There have been many noteworthy enhancements with JSON-P 1.1, such as:
- JSON Pointer: Allows for finding specific values in a JSON document
- JSON Patch: Allows for modifying operations on a JSON document
- JSON Merge Patch: Allows for using patch operations with merge
- Addition of JSON Collectors: Allows for accumulating JSON values from streams
Additionally, JsonReader has a new method called readValue() which returns a JSON value from the underlying input source. Similarly, JsonWriter was updated with another new method called write(JsonValue value), which allows for writing the JSON value to an output source. These additions were possible without breaking the earlier APIs because default methods were introduced in Java 8. We will go through more details about parsing and various other APIs in another chapter, but for now this should give you a starting point to begin exploring the APIs further.
- JavaScript全程指南
- 深入淺出Java虛擬機(jī):JVM原理與實(shí)戰(zhàn)
- NLTK基礎(chǔ)教程:用NLTK和Python庫構(gòu)建機(jī)器學(xué)習(xí)應(yīng)用
- TestNG Beginner's Guide
- FFmpeg入門詳解:音視頻流媒體播放器原理及應(yīng)用
- 第一行代碼 C語言(視頻講解版)
- 速學(xué)Python:程序設(shè)計(jì)從入門到進(jìn)階
- SQL Server實(shí)例教程(2008版)
- INSTANT Premium Drupal Themes
- Learning Shiny
- SCRATCH編程課:我的游戲我做主
- INSTANT PLC Programming with RSLogix 5000
- Learning Google Apps Script
- Image Processing with ImageJ(Second Edition)
- D Cookbook