Gson 的 JsonReader source code 理解

JsonReader 将JSON 内容作为Stream 读取, Stream包括 strings, numbers, booleans, and nulls 及 对象的开始有结束符, 另外还有数组。 

以读取一个简单的Json为例, 

public void testReadSimple() throws IOException {
		JsonReader reader = new JsonReader(reader("{\"name_test\": \"value_test\"}"));
		reader.beginObject();
		assertEquals("name_test", reader.nextName());
		assertEquals("value_test", reader.nextString());
		reader.endObject();
		assertEquals(JsonToken.END_DOCUMENT, reader.peek());
	}

主要的全局变量如下:

/**

   * 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.

   */

1. private final char[] buffer = new char[1024];

2. private int pos = 0;   // current position.

3. private int limit = 0;

4. int peeked = PEEKED_NONE;

 /*

   * The nesting stack. Using a manual array rather than an ArrayList saves 20%.

   */

5. private int[] stack = new int[32];

6. private int stackSize = 0;

  {

    stack[stackSize++] = JsonScope.EMPTY_DOCUMENT;

  }

7.   /** The input JSON. */

  private final Reader in;

其序列图如下表示 :

 

 

猜你喜欢

转载自ljhupahu.iteye.com/blog/2317277