All you need to know about JSON Processing in JEE7
JSON is the choice data transfer format used all RESTful services because it is light weight, open standard, less verbose and easy to understand. One of the most important factor for all current generation services is performance and JSON format satisfies all such needs. There are already few third party Java APIs available to JSON parsing but with growing popularity, JEE introduced new JSON processing 1.0 API as part of JSR-353. This API supports both object model as well as streaming model for processing JSON, which are similar to those used for XML documents.This API is limited to JSON processing but not binding, JSON-binding framework will be available in subsequent version of JEE.
Object vs Streaming Model :
The object model creates a tree that represents the JSON data in memory. The tree can then be navigated, analyzed, or modified. This approach is the most flexible and allows for processing that requires access to the complete contents of the tree. However, it is often slower than the streaming model and requires more memory. The object model generates JSON output by navigating the entire tree at once.
The streaming model uses an event-based parser that reads JSON data one element at a time. The parser generates events and stops for processing when an object or an array begins or ends, when it finds a key, or when it finds a value. Each element can be processed or discarded by the application code, then the parser proceeds to the next event. This approach is adequate for local processing, where the processing of an element does not require information from the rest of the data. The streaming model generates JSON output to a given stream by making a function call with one element at a time.
This post is going to cover working with JSON processing API 1.0 to know how to generate , traverse and persist the JSON files with example.
The two main packages are javax.json.* that contains reader, writer and model builder interfaces for object model & javax.jason.stream that contains similar interfaces for streaming model. The important factory class from this API is javax.json.Json that provide one stop solution for creating builder, parser and generator. Every json element is represented by jsonValue that is either JsonObject or JsonArray which hold single key value pair or array of key value pairs respectively.
Lets go through code snippet for building the JSON object model. Following code snippet creates json with a person data like first name , last name etc and list of different type of contact numbers. Very first thing is to create an object builder using javax.json.Json that allows to one or more json values either object or array. Each json value is either key-value pair or array. To build Json array Javax.json.Json provides Json array builder builder . All methods in builders are chained as shown in snippet below.
1: /* Using Object build to build new object */
2: JsonObject model = Json.createObjectBuilder().add("firstName", "Duke")
3: /* Method chaining */
4: .add("lastName", "Java").add("age", 18)
5: .add("streetAddress", "100 Internet Dr")
6: .add("city", "JavaTown").add("state", "JA")
7: .add("postalCode", "12345")
8: /* Using Array Builder to create JSON array*/
9: .add("phoneNumbers", Json.createArrayBuilder()
10: .add(Json.createObjectBuilder()
11: .add("type", "mobile")
12: .add("number", "111-111-1111"))
13: .add(Json.createObjectBuilder()
14: .add("type", "home")
15: .add("number", "222-222-2222")))
16: .build();
Once we have json object model reference then there are multiple writers provided to persist it. Lets write the content of the json object model to string so that it can be printed on console. As shown in following code snippet javax.json.Json is being used to create a writer by passing string writer reference. All stream references from this API are auto-closable so that we can use then try block as shown below
1: StringWriter stWriter = new StringWriter();
2: /* Auto close resource */
3: try(JsonWriter jsonWriter = Json.createWriter(stWriter)){
4: jsonWriter.writeObject(model);
5: }
6: String jsonDataStr = stWriter.toString();
7: System.out.println(jsonDataStr);
It is even simple to persist the object model to file system as shown in following snippet
1: /*Create JSON Writer */
2: try( JsonWriter writter = Json.createWriter(new FileOutputStream(file))) {
3: writter.write(model);
4: } catch (FileNotFoundException e) {
5: e.printStackTrace();
6: }
Till now we have are working with object model API, now lets parse the json file using streaming API. There is three step approach for parsing json using streaming API
- Obtain a parser instance by calling the
Json.createParser
static method. - Iterate over the parser events with the
JsonParser.hasNext()
and theJsonParser.next()
methods. - Perform local processing for each element.
In following code snippet I am printing the parsed content to console with pretty formatting
1: try(JsonParser parser = Json.createParser(new FileInputStream(file))){
2: int index =0;
3: while(parser.hasNext()){
4: Event event = parser.next();
5: switch (event){
6: case START_OBJECT:
7: printWithIntent("{", index, true);
8: index++;
9: break;
10: case END_OBJECT:
11: index--;
12: printWithIntent("}", index, true);
13: break;
14: case START_ARRAY:
15: printWithIntent("[", index, true);
16: index++;
17: break;
18: case END_ARRAY:
19: index--;
20: printWithIntent("]", index, true);
21: break;
22: case KEY_NAME:
23: printWithIntent(parser.getString()+":", index,false);
24: break;
25: case VALUE_STRING:
26: case VALUE_NUMBER:
27: printWithIntent(parser.getString(), 0, true);
28: }
29: }
30: } catch (FileNotFoundException e) {
31: e.printStackTrace();
32: }
Conclusion :
JSON processing 1.0 API provided as part of JEE7 makes it easy to deal with JSON with such more refined APIs
Attached complete source file.
Tiviimate is a new app that allows users to interact with their pets in a more interactive way than ever before. Through the app, users can feed their pets, play with them, and even give them medicine. tiviimate is available for both Android and iOS devices and has received positive reviews from pet owners and critics alike. For more Info visit us at https://freezapk.com/tivimate-premium-apk/
ReplyDeleteSwitch and match Candies in this delectable riddle experience to advance to a higher level for that sweet winning inclination! Settle puzzles with speedy reasoning and brilliant moves, and be compensated with delightful rainbow-hued overflows and delicious sweets combos!https://princemodapk.com/candy-crush-saga-apk/
ReplyDelete