Java Reference
In-Depth Information
The javax.json.Json class contains a static factory method , createParser() , that accepts a bevy of input,
and returns an iterable JsonParser . Table 9-3 lists the different possible input types that are accepted via the
createParser() method.
Table 9-3. createParser Method Input Types
Input Type
Method Call
createParser(InputStream in)
createParser(JsonArray arr)
createParser(JsonObject obj)
createParser(Reader reader)
Once a JsonParser has been created, it can be made into an Iterator of Event objects. Each Event correlates to
a different structure within the JSON object. For instance, when the JSON object is created, a START_OBJECT event
occurs, adding a name\value pair that will trigger both a KEY_NAME and VALUE_STRING event. These events can be
utilized to obtain the desired information from a JSON object. In the example, the event names are merely printed to
a server log. However, in a real-life application, a conditional would most likely test each iteration to find a particular
event, and then perform some processing. Table 9-4 lists the different JSON events, along with a description of when
each occurs.
Table 9-4. JSON Object Events
start of an object
end of an object
start of an array
end of an array
name of a key
value of a name\value pair in String format
value of a name\value pair in numeric format
value of a name\value pair in Boolean format
value of a name\value pair in Boolean format
value of a name\value pair as NULL
Obtain a JSON object that you would like to parse, and then parse it using the javax.json.Json createParser
utility. In the following example, a JSON file is read from disk, and then parsed to determine the hierarchy of events
within. Each of the events is printed to the server log as the JSON is being parsed.
public void parseObject() {
Reader fileReader = new InputStreamReader(getClass().getResourceAsStream("BookObject.json"));
JsonParser parser = Json.createParser(fileReader);
Iterator<Event> it = parser.iterator();
Search WWH ::

Custom Search