JsonWriter

Writes a JSON (RFC 7159) encoded value to a stream, one token at a time. The stream includes both literal values (strings, numbers, booleans and nulls) as well as the begin and end delimiters of objects and arrays.

Encoding JSON To encode your data as JSON, create a new {@code JsonWriter} . Each JSON document must contain one top-level array or object. Call methods on the writer as you walk the structure's contents, nesting arrays and objects as necessary:
  • To write arrays, first call beginArray . Write each of the array's elements with the appropriate methods or by nesting other arrays and objects. Finally close the array using endArray .
  • To write objects, first call beginObject . Write each of the object's properties by alternating calls to name with the property's value. Write property values with the appropriate method or by nesting other objects or arrays. Finally close the object using endObject .
Example Suppose we'd like to encode a stream of messages such as the following:
{@code * [ * { * "id": 912345678901, * "text": "How do I stream JSON in Java?", * "geo": null, * "user": { * "name": "json_newb", * "followers_count": 41 * } * }, * { * "id": 912345678902, * "text": "@json_newb just use JsonWriter!", * "geo": [50.454722, -104.606667], * "user": { * "name": "jesse", * "followers_count": 2 * } * } * ] * }
This code encodes the above structure:
{@code * public void writeJsonStream(BufferedSink sink, Listmessages) throws IOException {
 *   JsonWriter writer = JsonWriter.of(sink);
 *   writer.setIndent("  ");
 *   writeMessagesArray(writer, messages);
 *   writer.close();
 * }
 *
 * public void writeMessagesArray(JsonWriter writer, List

Each {@code JsonWriter} may be used to write a single JSON stream. Instances of this class are not thread safe. Calls that would result in a malformed JSON string will fail with an .

abstract class JsonWriter : Closeable, Flushable

Constructors

JsonWriter
Link copied to clipboard
open fun JsonWriter()

Functions

beginArray
Link copied to clipboard

Begins encoding a new array. Each call to this method must be paired with a call to .

abstract fun beginArray(): JsonWriter
beginFlatten
Link copied to clipboard

Cancels immediately-nested calls to beginArray or beginObject and their matching calls to endArray or endObject . Use this to compose JSON adapters without nesting.

For example, the following creates JSON with nested arrays: {@code [1,[2,3,4],5]} .

{@code * JsonAdapter

With flattening we can create JSON with a single array {@code [1,2,3,4,5]} :

{@code * JsonAdapter

This method flattens arrays within arrays:

{@code * Emit: [1, [2, 3, 4], 5] * To produce: [1, 2, 3, 4, 5] * }
It also flattens objects within objects. Do not call name before writing a flattened object.
{@code * Emit: {"a": 1, {"b": 2}, "c": 3} * To Produce: {"a": 1, "b": 2, "c": 3} * }
Other combinations are permitted but do not perform flattening. For example, objects inside of arrays are not flattened:
{@code * Emit: [1, {"b": 2}, 3, [4, 5], 6] * To Produce: [1, {"b": 2}, 3, 4, 5, 6] * }

This method returns an opaque token. Callers must match all calls to this method with a call to endFlatten with the matching token.

fun beginFlatten(): Int
beginObject
Link copied to clipboard

Begins encoding a new object. Each call to this method must be paired with a call to .

abstract fun beginObject(): JsonWriter
checkStack
Link copied to clipboard

Before pushing a value on the stack this confirms that the stack has capacity.

fun checkStack(): Boolean
close
Link copied to clipboard
abstract fun close()
endArray
Link copied to clipboard

Ends encoding the current array.

abstract fun endArray(): JsonWriter
endFlatten
Link copied to clipboard

Ends nested call flattening created by beginFlatten .

fun endFlatten(token: Int)
endObject
Link copied to clipboard

Ends encoding the current object.

abstract fun endObject(): JsonWriter
flush
Link copied to clipboard
abstract fun flush()
getPath
Link copied to clipboard

Returns a JsonPath to the current location in the JSON value.

fun getPath(): String
isLenient
Link copied to clipboard

Returns true if this writer has relaxed syntax rules.

fun isLenient(): Boolean
jsonValue
Link copied to clipboard

Encodes the value which may be a string, number, boolean, null, map, or list.

fun jsonValue(value: Any): JsonWriter
name
Link copied to clipboard

Encodes the property name.

abstract fun name(name: String): JsonWriter
nullValue
Link copied to clipboard

Encodes {@code null} .

abstract fun nullValue(): JsonWriter
of
Link copied to clipboard

Returns a new instance that writes UTF-8 encoded JSON to {@code sink} .

open fun of(sink: BufferedSink): JsonWriter
peekScope
Link copied to clipboard

Returns the scope on the top of the stack.

fun peekScope(): Int
promoteValueToName
Link copied to clipboard

Changes the writer to treat the next value as a string name. This is useful for map adapters so that arbitrary type adapters can use to write a name value.

In this example, calling this method allows two sequential calls to value to produce the object, {@code {"a": "b"}} .

{@code * JsonWriter writer = JsonWriter.of(...); * writer.beginObject(); * writer.promoteValueToName(); * writer.value("a"); * writer.value("b"); * writer.endObject(); * }

fun promoteValueToName()
pushScope
Link copied to clipboard
fun pushScope(newTop: Int)
replaceTop
Link copied to clipboard

Replace the value on the top of the stack with the given value.

fun replaceTop(topOfStack: Int)
setTag
Link copied to clipboard

Assigns the tag value using the given class key and value.

fun <T> setTag(clazz: Class<T>, value: T)
tag
Link copied to clipboard

Returns the tag value for the given class key.

fun <T> tag(clazz: Class<T>): T
value
Link copied to clipboard

Encodes {@code value} .

abstract fun value(value: Boolean): JsonWriter
abstract fun value(value: Double): JsonWriter
abstract fun value(value: Boolean): JsonWriter
abstract fun value(value: Number): JsonWriter
abstract fun value(value: String): JsonWriter
abstract fun value(value: Long): JsonWriter

Writes {@code source} directly without encoding its contents. Equivalent to {@code try * (BufferedSink sink = writer.valueSink()) { source.readAll(sink): }}

fun value(source: BufferedSource): JsonWriter
valueSink
Link copied to clipboard

Returns a BufferedSink into which arbitrary data can be written without any additional encoding. You must call before interacting with this {@code * JsonWriter} instance again.

Since no validation is performed, options like setSerializeNulls and other writer configurations are not respected.

abstract fun valueSink(): BufferedSink

Properties

flattenStackSize
Link copied to clipboard

Controls the deepest stack size that has begin/end pairs flattened:

  • If -1, no begin/end pairs are being suppressed.
  • If positive, this is the deepest stack size whose begin/end pairs are eligible to be flattened.
  • If negative, it is the bitwise inverse (~) of the deepest stack size whose begin/end pairs have been flattened.

We differentiate between what layer would be flattened (positive) from what layer is being flattened (negative) so that we don't double-flatten.

To accommodate nested flattening we require callers to track the previous state when they provide a new state. The previous state is returned from beginFlatten and restored with endFlatten .

open val flattenStackSize: Int
indent
Link copied to clipboard

A string containing a full set of spaces for a single level of indentation, or null for no pretty printing.

open var indent: String
lenient
Link copied to clipboard
open var lenient: Boolean
pathIndices
Link copied to clipboard
open val pathIndices: Array<Int>
pathNames
Link copied to clipboard
open val pathNames: Array<String>
promoteValueToName
Link copied to clipboard
open val promoteValueToName: Boolean
scopes
Link copied to clipboard
open val scopes: Array<Int>
serializeNulls
Link copied to clipboard
open var serializeNulls: Boolean
stackSize
Link copied to clipboard
open val stackSize: Int

Inheritors

JsonUtf8Writer
Link copied to clipboard
JsonValueWriter
Link copied to clipboard