Json Writer
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 .
{@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 * } * } * ] * }
{@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 .
Constructors
Functions
Properties
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 .