nextSource

abstract fun nextSource(): BufferedSource

Returns the next value as a stream of UTF-8 bytes and consumes it.

The following program demonstrates how JSON bytes are returned from an enclosing stream as their original bytes, including their original whitespace:

String json = "{\"a\": [4,  5  ,6.0, {\"x\":7}, 8], \"b\": 9}";
JsonReader reader = JsonReader.of(new Buffer().writeUtf8(json));
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
try (BufferedSource bufferedSource = reader.nextSource()) {
  assertThat(bufferedSource.readUtf8()).isEqualTo("[4,  5  ,6.0, {\"x\":7}, 8]");
}
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextInt()).isEqualTo(9);
reader.endObject();

This reads an entire value: composite objects like arrays and objects are returned in their entirety. The stream starts with the first character of the value (typically [, { , or ") and ends with the last character of the object (typically ], }, or ").

The returned source may not be used after any other method on this JsonReader is called. For example, the following code crashes with an exception:

JsonReader reader = ...
reader.beginArray();
BufferedSource source = reader.nextSource();
reader.endArray();
source.readUtf8(); // Crash!

The returned bytes are not validated. This method assumes the stream is well-formed JSON and only attempts to find the value's boundary in the byte stream. It is the caller's responsibility to check that the returned byte stream is a valid JSON value.

Closing the returned source does not close this reader.