AndBase开发框架  1.6
 全部  命名空间 文件 函数 变量 枚举值 
Public 成员函数 | 包函数 | Private 成员函数 | Private 属性 | 静态 Private 属性 | 所有成员列表
com.google.gson.stream.JsonReader类 参考
类 com.google.gson.stream.JsonReader 继承关系图:
com.google.gson.internal.bind.JsonTreeReader

Public 成员函数

 JsonReader (Reader in)
 
final void setLenient (boolean lenient)
 
final boolean isLenient ()
 
void beginArray () throws IOException
 
void endArray () throws IOException
 
void beginObject () throws IOException
 
void endObject () throws IOException
 
boolean hasNext () throws IOException
 
JsonToken peek () throws IOException
 
String nextName () throws IOException
 
String nextString () throws IOException
 
boolean nextBoolean () throws IOException
 
void nextNull () throws IOException
 
double nextDouble () throws IOException
 
long nextLong () throws IOException
 
int nextInt () throws IOException
 
void close () throws IOException
 
void skipValue () throws IOException
 

包函数

 [instance initializer]
 

Private 成员函数

void expect (JsonToken expected) throws IOException
 
void consumeNonExecutePrefix () throws IOException
 
JsonToken advance () throws IOException
 
void push (JsonScope newTop)
 

Private 属性

final StringPool stringPool = new StringPool()
 
final Reader in
 
boolean lenient = false
 
final char[] buffer = new char[1024]
 
int pos = 0
 
int limit = 0
 
int bufferStartLine = 1
 
int bufferStartColumn = 1
 
JsonScope[] stack = new JsonScope[32]
 
int stackSize = 0
 
JsonToken token
 
String name
 
String value
 
int valuePos
 
int valueLength
 
boolean skipping = false
 

静态 Private 属性

static final char[] NON_EXECUTE_PREFIX = ")]}'\n".toCharArray()
 
static final String TRUE = "true"
 
static final String FALSE = "false"
 

详细描述

Reads a JSON (RFC 4627) 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 JSON

To create a recursive descent parser for your own JSON streams, first create an entry point method that creates a

.

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.

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 either nextNull() or skipValue().

Example

Suppose we'd like to parse a stream of messages such as the following:

[
{
"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
}
}
]

This code implements the parser for the above structure:

public List<Message> readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMessagesArray(reader);
} finally {
reader.close();
}
}
public List<Message> readMessagesArray(JsonReader reader) throws IOException {
List<Message> messages = new ArrayList<Message>();
reader.beginArray();
while (reader.hasNext()) {
messages.add(readMessage(reader));
}
reader.endArray();
return messages;
}
public Message readMessage(JsonReader reader) throws IOException {
long id = -1;
String text = null;
User user = null;
List<Double> geo = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("id")) {
id = reader.nextLong();
} else if (name.equals("text")) {
text = reader.nextString();
} else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
geo = readDoublesArray(reader);
} else if (name.equals("user")) {
user = readUser(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Message(id, text, user, geo);
}
public List<Double> readDoublesArray(JsonReader reader) throws IOException {
List<Double> doubles = new ArrayList<Double>();
reader.beginArray();
while (reader.hasNext()) {
doubles.add(reader.nextDouble());
}
reader.endArray();
return doubles;
}
public User readUser(JsonReader reader) throws IOException {
String username = null;
int followersCount = -1;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("name")) {
username = reader.nextString();
} else if (name.equals("followers_count")) {
followersCount = reader.nextInt();
} else {
reader.skipValue();
}
}
reader.endObject();
return new User(username, followersCount);
}

Number Handling

This 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

[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

9007199254740993

cannot be represented exactly on that platform. To minimize precision loss, extremely large values should be written and read as strings in JSON.

Non-Execute Prefix

Web servers that serve private data using JSON may be vulnerable to Cross-site request forgery attacks. In such an attack, a malicious site gains access to a private JSON file by executing it with an HTML

<script>

tag.

Prefixing JSON files with ")]}'\n" makes them non-executable by

<script>

tags, disarming the attack. Since the prefix is malformed JSON, strict parsing fails when it is encountered. This class permits the non-execute prefix when lenient parsing is enabled.

Each

may be used to read a single JSON stream. Instances of this class are not thread safe.

作者
Jesse Wilson
自从
1.6

构造及析构函数说明

com.google.gson.stream.JsonReader.JsonReader ( Reader  in)
inline

Creates a new instance that reads a JSON-encoded stream from

.

成员函数说明

com.google.gson.stream.JsonReader.[instance initializer] ( )
inlinepackage
JsonToken com.google.gson.stream.JsonReader.advance ( ) throws IOException
inlineprivate

Advances the cursor in the JSON stream to the next token.

void com.google.gson.stream.JsonReader.beginArray ( ) throws IOException
inline

Consumes the next token from the JSON stream and asserts that it is the beginning of a new array.

void com.google.gson.stream.JsonReader.beginObject ( ) throws IOException
inline

Consumes the next token from the JSON stream and asserts that it is the beginning of a new object.

void com.google.gson.stream.JsonReader.close ( ) throws IOException
inline

Closes this JSON reader and the underlying Reader.

void com.google.gson.stream.JsonReader.consumeNonExecutePrefix ( ) throws IOException
inlineprivate

Consumes the non-execute prefix if it exists.

void com.google.gson.stream.JsonReader.endArray ( ) throws IOException
inline

Consumes the next token from the JSON stream and asserts that it is the end of the current array.

void com.google.gson.stream.JsonReader.endObject ( ) throws IOException
inline

Consumes the next token from the JSON stream and asserts that it is the end of the current array.

void com.google.gson.stream.JsonReader.expect ( JsonToken  expected) throws IOException
inlineprivate

Consumes

expected

.

boolean com.google.gson.stream.JsonReader.hasNext ( ) throws IOException
inline

Returns true if the current array or object has another element.

final boolean com.google.gson.stream.JsonReader.isLenient ( )
inline

Returns true if this parser is liberal in what it accepts.

boolean com.google.gson.stream.JsonReader.nextBoolean ( ) throws IOException
inline

Returns the boolean value of the next token, consuming it.

异常
IllegalStateExceptionif the next token is not a boolean or if this reader is closed.
double com.google.gson.stream.JsonReader.nextDouble ( ) throws IOException
inline

Returns the double value of the next token, consuming it. If the next token is a string, this method will attempt to parse it as a double using Double#parseDouble(String).

异常
IllegalStateExceptionif the next token is not a literal value.
NumberFormatExceptionif the next literal value cannot be parsed as a double, or is non-finite.
int com.google.gson.stream.JsonReader.nextInt ( ) throws IOException
inline

Returns the int value of the next token, consuming it. If the next token is a string, this method will attempt to parse it as an int. If the next token's numeric value cannot be exactly represented by a Java

int

, this method throws.

异常
IllegalStateExceptionif the next token is not a literal value.
NumberFormatExceptionif the next literal value cannot be parsed as a number, or exactly represented as an int.
long com.google.gson.stream.JsonReader.nextLong ( ) throws IOException
inline

Returns the long value of the next token, consuming it. If the next token is a string, this method will attempt to parse it as a long. If the next token's numeric value cannot be exactly represented by a Java

long

, this method throws.

异常
IllegalStateExceptionif the next token is not a literal value.
NumberFormatExceptionif the next literal value cannot be parsed as a number, or exactly represented as a long.
String com.google.gson.stream.JsonReader.nextName ( ) throws IOException
inline

Returns the next token, a property name, and consumes it.

异常
IOExceptionif the next token in the stream is not a property name.
void com.google.gson.stream.JsonReader.nextNull ( ) throws IOException
inline

Consumes the next token from the JSON stream and asserts that it is a literal null.

异常
IllegalStateExceptionif the next token is not null or if this reader is closed.
String com.google.gson.stream.JsonReader.nextString ( ) throws IOException
inline

Returns the string value of the next token, consuming it. If the next token is a number, this method will return its string form.

异常
IllegalStateExceptionif the next token is not a string or if this reader is closed.
JsonToken com.google.gson.stream.JsonReader.peek ( ) throws IOException
inline

Returns the type of the next token without consuming it.

void com.google.gson.stream.JsonReader.push ( JsonScope  newTop)
inlineprivate
final void com.google.gson.stream.JsonReader.setLenient ( boolean  lenient)
inline

Configure this parser to be be liberal in what it accepts. By default, this parser is strict and only accepts JSON as specified by RFC 4627. Setting the parser to lenient causes it to ignore the following syntax errors:

  • Streams that start with the non-execute prefix, ")]}'\n".
  • Streams that include multiple top-level values. With strict parsing, each stream must contain exactly one top-level value.
  • Top-level values of any type. With strict parsing, the top-level value must be an object or an array.
  • Numbers may be NaNs or infinities.
  • End of line comments starting with
    //
    or
    #
    and ending with a newline character.
  • C-style comments starting with
    /*
    and ending with
    *
    /
    . Such comments may not be nested.
  • Names that are unquoted or
    'single quoted'
    .
  • Strings that are unquoted or
    'single quoted'
    .
  • Array elements separated by
    ;
    instead of
    ,
    .
  • Unnecessary array separators. These are interpreted as if null was the omitted value.
  • Names and values separated by
    =
    or
    =>
    instead of
    :
    .
  • Name/value pairs separated by
    ;
    instead of
    ,
    .
void com.google.gson.stream.JsonReader.skipValue ( ) throws IOException
inline

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 unhandled values.

类成员变量说明

final char [] com.google.gson.stream.JsonReader.buffer = new char[1024]
private

Use a manual buffer to easily read and unread upcoming characters, and also so we can create strings without an intermediate StringBuilder. We decode literals directly out of this buffer, so it must be at least as long as the longest token that can be reported as a number.

int com.google.gson.stream.JsonReader.bufferStartColumn = 1
private
int com.google.gson.stream.JsonReader.bufferStartLine = 1
private
final String com.google.gson.stream.JsonReader.FALSE = "false"
staticprivate
final Reader com.google.gson.stream.JsonReader.in
private

The input JSON.

boolean com.google.gson.stream.JsonReader.lenient = false
private

True to accept non-spec compliant JSON

int com.google.gson.stream.JsonReader.limit = 0
private
String com.google.gson.stream.JsonReader.name
private

The text of the next name.

final char [] com.google.gson.stream.JsonReader.NON_EXECUTE_PREFIX = ")]}'\n".toCharArray()
staticprivate

The only non-execute prefix this parser permits

int com.google.gson.stream.JsonReader.pos = 0
private
boolean com.google.gson.stream.JsonReader.skipping = false
private

True if we're currently handling a skipValue() call.

JsonScope [] com.google.gson.stream.JsonReader.stack = new JsonScope[32]
private
int com.google.gson.stream.JsonReader.stackSize = 0
private
final StringPool com.google.gson.stream.JsonReader.stringPool = new StringPool()
private
JsonToken com.google.gson.stream.JsonReader.token
private

The type of the next token to be returned by peek and advance. If null, peek() will assign a value.

final String com.google.gson.stream.JsonReader.TRUE = "true"
staticprivate
String com.google.gson.stream.JsonReader.value
private
int com.google.gson.stream.JsonReader.valueLength
private
int com.google.gson.stream.JsonReader.valuePos
private

该类的文档由以下文件生成: