-
- All Implemented Interfaces:
-
java.io.Closeable,java.lang.AutoCloseable
public abstract class JsonReader implements Closeable
Reads a JSON (RFC 7159) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.
Parsing JSONTo create a recursive descent parser for your own JSON streams, first create an entry point method that creates a{@code JsonReader}.Next, create handler methods for each structure in your JSON text. You'll need a method for each object type and for each array type.
- Within array handling methods, first call to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext is false. Finally, read the array's closing bracket by calling .
- Within object handling methods, first call to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext is false. Finally, read the object's closing brace by calling endObject.
When a nested object or array is encountered, delegate to the corresponding handler method.
When an unknown name is encountered, strict parsers should fail with an exception. Lenient parsers should call skipValue to recursively skip the value's nested tokens, which may otherwise conflict.
If a value may be null, you should first check using peek. Null literals can be consumed using skipValue.
ExampleSuppose we'd like to parse a stream of messages such as the following:
This code implements the parser for the above structure:{@code * [ * { * "id": 912345678901, * "text": "How do I read a JSON stream in Java?", * "geo": null, * "user": { * "name": "json_newb", * "followers_count": 41 * } * }, * { * "id": 912345678902, * "text": "@json_newb just use JsonReader!", * "geo": [50.454722, -104.606667], * "user": { * "name": "jesse", * "followers_count": 2 * } * } * ]}
Number HandlingThis reader permits numeric values to be read as strings and string values to be read as numbers. For example, both elements of the JSON array{@code * * public ListreadJsonStream(BufferedSource source) throws IOException { * JsonReader reader = JsonReader.of(source); * try { * return readMessagesArray(reader); * } finally { * reader.close(); * } * } * * public List{@code * [1, "1"]}may be read using either nextInt or nextString. This behavior is intended to prevent lossy numeric conversions: double is JavaScript's only numeric type and very large values like{@code * 9007199254740993}cannot be represented exactly on that platform. To minimize precision loss, extremely large values should be written and read as strings in JSON.Each
{@code JsonReader}may be used to read a single JSON stream. Instances of this class are not thread safe.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public final classJsonReader.OptionsA set of strings to be chosen with selectName. This preparesthe encoded values of the strings so they can be read directly from the input source.
public enumJsonReader.TokenA structure, name, or value type in a JSON-encoded string.
-
Method Summary
Modifier and Type Method Description static JsonReaderof(BufferedSource source)Returns a new instance that reads UTF-8 encoded JSON from {@code source}.abstract voidbeginArray()Consumes the next token from the JSON stream and asserts that it is the beginning of a newarray. abstract voidendArray()Consumes the next token from the JSON stream and asserts that it is theend of the current array. abstract voidbeginObject()Consumes the next token from the JSON stream and asserts that it is the beginning of a newobject. abstract voidendObject()Consumes the next token from the JSON stream and asserts that it is the end of the currentobject. abstract booleanhasNext()Returns true if the current array or object has another element. abstract JsonReader.Tokenpeek()Returns the type of the next token without consuming it. abstract StringnextName()Returns the next token, a property name, and consumes it. abstract intselectName(JsonReader.Options options)If the next token is a property name that's in {@code options}, thisconsumes it and returns its index.abstract voidskipName()Skips the next token, consuming it. abstract StringnextString()Returns the string value of the next token, consuming it. abstract booleannextBoolean()Returns the boolean value of the next token, consuming it. abstract doublenextDouble()Returns the double value of the next token, consuming it. abstract intnextInt()Returns the int value of the next token, consuming it. abstract voidskipValue()Skips the next value recursively. final StringgetPath()Returns a JsonPath tothe current location in the JSON value. -
-
Method Detail
-
of
static JsonReader of(BufferedSource source)
Returns a new instance that reads UTF-8 encoded JSON from
{@code source}.
-
beginArray
abstract void beginArray()
Consumes the next token from the JSON stream and asserts that it is the beginning of a newarray.
-
endArray
abstract void endArray()
Consumes the next token from the JSON stream and asserts that it is theend of the current array.
-
beginObject
abstract void beginObject()
Consumes the next token from the JSON stream and asserts that it is the beginning of a newobject.
-
endObject
abstract void endObject()
Consumes the next token from the JSON stream and asserts that it is the end of the currentobject.
-
hasNext
abstract boolean hasNext()
Returns true if the current array or object has another element.
-
peek
abstract JsonReader.Token peek()
Returns the type of the next token without consuming it.
-
selectName
abstract int selectName(JsonReader.Options options)
If the next token is a property name that's in
{@code options}, thisconsumes it and returns its index. Otherwise this returns -1 and no name is consumed.
-
skipName
abstract void skipName()
Skips the next token, consuming it. This method is intended for use when the JSON token streamcontains unrecognized or unhandled names.
This throws a JsonDataException if this parser has been configured to fail on unknown names.
-
nextString
abstract String nextString()
Returns the string value of the next token, consuming it. If the nexttoken is a number, this method will return its string form.
-
nextBoolean
abstract boolean nextBoolean()
Returns the boolean value of the next token, consuming it.
-
nextDouble
abstract double nextDouble()
-
nextInt
abstract int nextInt()
Returns the int value of the next token, consuming it. If the nexttoken is a string, this method will attempt to parse it as an int. If the next token's numericvalue cannot be exactly represented by a Java
{@code int}, this method throws.
-
skipValue
abstract void skipValue()
Skips the next value recursively. If it is an object or array, all nested elements are skipped.This method is intended for use when the JSON token stream contains unrecognized or unhandledvalues.
This throws a JsonDataException if this parser has been configured to fail on unknown values.
-
-
-
-