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
InputStream
createParser(InputStream in)
JsonArray
createParser(JsonArray arr)
JsonObject
createParser(JsonObject obj)
Reader
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
Event
Occurrence
START_OBJECT
start of an object
END_OBJECT
end of an object
START_ARRAY
start of an array
END_ARRAY
end of an array
KEY_NAME
name of a key
VALUE_STRING
value of a name\value pair in String format
VALUE_NUMBER
value of a name\value pair in numeric format
VALUE_TRUE
value of a name\value pair in Boolean format
VALUE_FALSE
value of a name\value pair in Boolean format
VALUE_NULL
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