Interface JsonParser
-
- All Superinterfaces:
AutoCloseable,Closeable
public interface JsonParser extends Closeable
Provides forward, read-only access to JSON data in a streaming way. This is the most efficient way for reading JSON data. This is the only way to parse and process JSON data that are too big to be loaded in memory.The class
Jsoncontains methods to create parsers from input sources (InputStreamandReader).The following example demonstrates how to create a parser from a string that contains an empty JSON array:
JsonParser parser = Json.createParser(new StringReader("[]"));The class
JsonParserFactoryalso contains methods to createJsonParserinstances.JsonParserFactoryis preferred when creating multiple parser instances. A sample usage is shown in the following example:JsonParserFactory factory = Json.createParserFactory(); JsonParser parser1 = factory.createParser(...); JsonParser parser2 = factory.createParser(...);JsonParserparses JSON using the pull parsing programming model. In this model the client code controls the thread and calls the methodnext()to advance the parser to the next state after processing each element. The parser can generate the following events:START_OBJECT,END_OBJECT,START_ARRAY,END_ARRAY,KEY_NAME,VALUE_STRING,VALUE_NUMBER,VALUE_TRUE,VALUE_FALSE, andVALUE_NULL.For example, for an empty JSON object ({ }), the parser generates the event
START_OBJECTwith the first call to the methodnext()and the eventEND_OBJECTwith the second call to the methodnext(). The following code demonstrates how to access these events:Event event = parser.next(); // START_OBJECT event = parser.next(); // END_OBJECTFor example, for the following JSON:
{ "firstName": "John", "lastName": "Smith", "age": 25, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }calls to the method
next()result in parse events at the specified locations below (marked in bold):{START_OBJECT "firstName"KEY_NAME: "John"VALUE_STRING, "lastName"KEY_NAME: "Smith"VALUE_STRING, "age"KEY_NAME: 25VALUE_NUMBER, "phoneNumber"KEY_NAME : [START_ARRAY {START_OBJECT "type"KEY_NAME: "home"VALUE_STRING, "number"KEY_NAME: "212 555-1234"VALUE_STRING }END_OBJECT, {START_OBJECT "type"KEY_NAME: "fax"VALUE_STRING, "number"KEY_NAME: "646 555-4567"VALUE_STRING }END_OBJECT ]END_ARRAY }END_OBJECTThe methodsnext()andhasNext()enable iteration over parser events to process JSON data.JsonParserprovides get methods to obtain the value at the current state of the parser. For example, the following code shows how to obtain the value "John" from the JSON above:
Starting in version 1.1, it is possible to build a partial JSON object model from the stream, at the current parser position. The methodsEvent event = parser.next(); // START_OBJECT event = parser.next(); // KEY_NAME event = parser.next(); // VALUE_STRING parser.getString(); // "John"getArray()andgetObject()can be used to read in aJsonArrayorJsonObject. For example, the following code shows how to obtain the phoneNumber in a JsonArray, from the JSON above:
The methodswhile (parser.hasNext() { Event event = parser.next(); if (event == JsonParser.Event.KEY_NAME ) { String key = getString(); event = parser.next(); if (key.equals("phoneNumber") { JsonArray phones = parser.getArray(); } } }getArrayStream()andgetObjectStream()can be used to get a stream of the elements of aJsonArrayorJsonObject. For example, the following code shows another way to obtain John's phoneNumber in aJsonArray:
The methodsEvent event = parser.next(); // START_OBJECT JsonArray phones = (JsonArray) parser.getObjectStream().filter(e->e.getKey().equals("phoneNumber")) .map(e->e.getValue()) .findFirst() .get();skipArray()andskipObject()can be used to skip tokens and position the parser toEND_ARRAYorEND_OBJECT.JsonParsercan be used to parse sequence of JSON values that are not enclosed in a JSON array, e.g. { } { }. The following code demonstrates how to parse such sequence.JsonParser parser = Json.createParser(...); while (parser.hasNext) { parser.next(); // advance parser state JsonValue value = parser.getValue(); }- See Also:
Json,JsonParserFactory
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static classJsonParser.EventAn event fromJsonParser.
-
Method Summary
All Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description voidclose()Closes this parser and frees any resources associated with the parser.default JsonArraygetArray()Returns aJsonArrayand advance the parser to the the correspondingEND_ARRAY.default Stream<JsonValue>getArrayStream()Returns a stream of theJsonArrayelements.BigDecimalgetBigDecimal()Returns a JSON number as aBigDecimal.intgetInt()Returns a JSON number as an integer.JsonLocationgetLocation()Return the location that corresponds to the parser's current state in the JSON input source.longgetLong()Returns a JSON number as a long.default JsonObjectgetObject()Returns aJsonObjectand advances the parser to the correspondingEND_OBJECT.default Stream<Map.Entry<String,JsonValue>>getObjectStream()Returns a stream of theJsonObject's name/value pairs.StringgetString()Returns aStringfor the name in a name/value pair, for a string value or a number value.default JsonValuegetValue()Returns aJsonValueat the current parser position.default Stream<JsonValue>getValueStream()Returns a stream ofJsonValuefrom a sequence of JSON values.booleanhasNext()Returnstrueif there are more parsing states.booleanisIntegralNumber()Returns true if the JSON number at the current parser state is a integral number.JsonParser.Eventnext()Returns the event for the next parsing state.default voidskipArray()Advance the parser toEND_ARRAY.default voidskipObject()Advance the parser toEND_OBJECT.
-
-
-
Method Detail
-
hasNext
boolean hasNext()
Returnstrueif there are more parsing states. This method returnsfalseif the parser reaches the end of the JSON text.- Returns:
trueif there are more parsing states.- Throws:
JsonException- if an i/o error occurs (IOException would be cause of JsonException)JsonParsingException- if the parser encounters invalid JSON when advancing to next state.
-
next
JsonParser.Event next()
Returns the event for the next parsing state.- Returns:
- the event for the next parsing state
- Throws:
JsonException- if an i/o error occurs (IOException would be cause of JsonException)JsonParsingException- if the parser encounters invalid JSON when advancing to next state.NoSuchElementException- if there are no more parsing states.
-
getString
String getString()
Returns aStringfor the name in a name/value pair, for a string value or a number value. This method should only be called when the parser state isJsonParser.Event.KEY_NAME,JsonParser.Event.VALUE_STRING, orJsonParser.Event.VALUE_NUMBER.- Returns:
- a name when the parser state is
JsonParser.Event.KEY_NAMEa string value when the parser state isJsonParser.Event.VALUE_STRINGa number value when the parser state isJsonParser.Event.VALUE_NUMBER - Throws:
IllegalStateException- when the parser state is notKEY_NAME,VALUE_STRING, orVALUE_NUMBER
-
isIntegralNumber
boolean isIntegralNumber()
Returns true if the JSON number at the current parser state is a integral number. ABigDecimalmay be used to store the value internally and this method semantics are defined using itsscale(). If the scale is zero, then it is considered integral type. This integral type information can be used to invoke an appropriate accessor method to obtain a numeric value as in the following example:JsonParser parser = ... if (parser.isIntegralNumber()) { parser.getInt(); // or other methods to get integral value } else { parser.getBigDecimal(); }- Returns:
- true if this number is a integral number, otherwise false
- Throws:
IllegalStateException- when the parser state is notVALUE_NUMBER
-
getInt
int getInt()
Returns a JSON number as an integer. The returned value is equal tonew BigDecimal(getString()).intValue(). Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign. This method should only be called when the parser state isJsonParser.Event.VALUE_NUMBER.- Returns:
- an integer for a JSON number
- Throws:
IllegalStateException- when the parser state is notVALUE_NUMBER- See Also:
BigDecimal.intValue()
-
getLong
long getLong()
Returns a JSON number as a long. The returned value is equal tonew BigDecimal(getString()).longValue(). Note that this conversion can lose information about the overall magnitude and precision of the number value as well as return a result with the opposite sign. This method is only called when the parser state isJsonParser.Event.VALUE_NUMBER.- Returns:
- a long for a JSON number
- Throws:
IllegalStateException- when the parser state is notVALUE_NUMBER- See Also:
BigDecimal.longValue()
-
getBigDecimal
BigDecimal getBigDecimal()
Returns a JSON number as aBigDecimal. TheBigDecimalis created usingnew BigDecimal(getString()). This method should only called when the parser state isJsonParser.Event.VALUE_NUMBER.- Returns:
- a
BigDecimalfor a JSON number - Throws:
IllegalStateException- when the parser state is notVALUE_NUMBER
-
getLocation
JsonLocation getLocation()
Return the location that corresponds to the parser's current state in the JSON input source. The location information is only valid in the current parser state (or until the parser is advanced to a next state).- Returns:
- a non-null location corresponding to the current parser state in JSON input source
-
getObject
default JsonObject getObject()
Returns aJsonObjectand advances the parser to the correspondingEND_OBJECT.- Returns:
- the
JsonObjectat the current parser position - Throws:
IllegalStateException- when the parser state is notSTART_OBJECT- Since:
- 1.1
-
getValue
default JsonValue getValue()
Returns aJsonValueat the current parser position. If the parser state isSTART_ARRAY, the behavior is the same asgetArray(). If the parser state isSTART_OBJECT, the behavior is the same asgetObject(). For all other cases, if applicable, the JSON value is read and returned.- Returns:
- the
JsonValueat the current parser position. - Throws:
IllegalStateException- when the parser state isEND_OBJECTorEND_ARRAY- Since:
- 1.1
-
getArray
default JsonArray getArray()
Returns aJsonArrayand advance the parser to the the correspondingEND_ARRAY.- Returns:
- the
JsonArrayat the current parser position - Throws:
IllegalStateException- when the parser state is notSTART_ARRAY- Since:
- 1.1
-
getArrayStream
default Stream<JsonValue> getArrayStream()
Returns a stream of theJsonArrayelements. The parser state must beSTART_ARRAY. The elements are read lazily, on an as-needed basis, as required by the stream operations. If the stream operations do not consume all of the array elements,skipArray()can be used to skip the unprocessed array elements.- Returns:
- a stream of elements of the
JsonArray - Throws:
IllegalStateException- when the parser state is notSTART_ARRAY- Since:
- 1.1
-
getObjectStream
default Stream<Map.Entry<String,JsonValue>> getObjectStream()
Returns a stream of theJsonObject's name/value pairs. The parser state must beSTART_OBJECT. The name/value pairs are read lazily, on an as-needed basis, as required by the stream operations. If the stream operations do not consume all of the object's name/value pairs,skipObject()can be used to skip the unprocessed elements.- Returns:
- a stream of name/value pairs of the
JsonObject - Throws:
IllegalStateException- when the parser state is notSTART_OBJECT- Since:
- 1.1
-
getValueStream
default Stream<JsonValue> getValueStream()
Returns a stream ofJsonValuefrom a sequence of JSON values. The values are read lazily, on an as-needed basis, as needed by the stream operations.- Returns:
- a Stream of
JsonValue - Throws:
IllegalStateException- if the parser is in an array or object.- Since:
- 1.1
-
skipArray
default void skipArray()
Advance the parser toEND_ARRAY. If the parser is in array context, i.e. it has previously encountered aSTART_ARRAYwithout encountering the correspondingEND_ARRAY, the parser is advanced to the correspondingEND_ARRAY. If the parser is not in any array context, nothing happens.- Since:
- 1.1
-
skipObject
default void skipObject()
Advance the parser toEND_OBJECT. If the parser is in object context, i.e. it has previously encountered aSTART_OBJECTwithout encountering the correspondingEND_OBJECT, the parser is advanced to the correspondingEND_OBJECT. If the parser is not in any object context, nothing happens.- Since:
- 1.1
-
close
void close()
Closes this parser and frees any resources associated with the parser. This method closes the underlying input source.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
JsonException- if an i/o error occurs (IOException would be cause of JsonException)
-
-