Top Description Fields Constructors Methods
com.google.gson.stream

public Class JsonWriter

extends Object
implements Closeable, Flushable
Class Inheritance
All Implemented Interfaces
java.io.Flushable, java.io.Closeable, java.lang.AutoCloseable
Known Direct Subclasses
com.google.gson.internal.bind.JsonTreeWriter
Static Imports
com.google.gson.stream.JsonScope.DANGLING_NAME, .JsonScope.EMPTY_ARRAY, .JsonScope.EMPTY_DOCUMENT, .JsonScope.EMPTY_OBJECT, .JsonScope.NONEMPTY_ARRAY, .JsonScope.NONEMPTY_DOCUMENT, .JsonScope.NONEMPTY_OBJECT

Writes a JSON (RFC 8259) 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 JsonWriter. Call methods on the writer as you walk the structure's contents, nesting arrays and objects as necessary:

Configuration

The behavior of this writer can be customized with the following methods: The default configuration of JsonWriter instances used internally by the com.google.gson.Gson class differs, and can be adjusted with the various com.google.gson.GsonBuilder methods.

Example

Suppose we'd like to encode a stream of messages such as the following:
[
  {
    "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:
public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException {
  JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
  writer.setIndent("    ");
  writeMessagesArray(writer, messages);
  writer.close();
}

public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException {
  writer.beginArray();
  for (Message message : messages) {
    writeMessage(writer, message);
  }
  writer.endArray();
}

public void writeMessage(JsonWriter writer, Message message) throws IOException {
  writer.beginObject();
  writer.name("id").value(message.getId());
  writer.name("text").value(message.getText());
  if (message.getGeo() != null) {
    writer.name("geo");
    writeDoublesArray(writer, message.getGeo());
  } else {
    writer.name("geo").nullValue();
  }
  writer.name("user");
  writeUser(writer, message.getUser());
  writer.endObject();
}

public void writeUser(JsonWriter writer, User user) throws IOException {
  writer.beginObject();
  writer.name("name").value(user.getName());
  writer.name("followers_count").value(user.getFollowersCount());
  writer.endObject();
}

public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException {
  writer.beginArray();
  for (Double value : doubles) {
    writer.value(value);
  }
  writer.endArray();
}

Each 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 IllegalStateException.

Author
Jesse Wilson
Since
1.6

Field Summary

Modifier and TypeField and Description
private String
private String
private String
private FormattingStyle
private static final String[]
private boolean
private final Writer
out

The JSON output destination

private static final String[]
private boolean
private int[]
private int
private Strictness
private boolean
private static final Pattern

Constructor Summary

AccessConstructor and Description
public
JsonWriter(Writer out)

Creates a new instance that writes a JSON-encoded stream to out.

Method Summary

Modifier and TypeMethod and Description
private static boolean
alwaysCreatesValidJsonNumber(Class<? extends Number> c)

Returns whether the toString() of c will always return a valid JSON number.

private void
beforeName()

Inserts any necessary separators and whitespace before a name.

private void
beforeValue()

Inserts any necessary separators and whitespace before a literal value, inline array, or inline object.

public JsonWriter

Returns:

this writer.
beginArray
()

Begins encoding a new array.

public JsonWriter

Returns:

this writer.
beginObject
()

Begins encoding a new object.

public void
close()

Implements java.io.Closeable.close.

Flushes and closes this writer and the underlying Writer.

private JsonWriter
closeScope(int empty, int nonempty, char closeBracket)

Closes the current scope by appending any necessary whitespace and the given bracket.

public JsonWriter

Returns:

this writer.
endArray
()

Ends encoding the current array.

public JsonWriter

Returns:

this writer.
endObject
()

Ends encoding the current object.

public void
flush()

Implements java.io.Flushable.flush.

Ensures all buffered data is written to the underlying Writer and flushes that writer.

public final FormattingStyle

Returns:

the FormattingStyle that will be used.
getFormattingStyle
()

Returns the pretty printing style used by this writer.

public final boolean
getSerializeNulls()

Returns true if object members are serialized when their value is null.

public final Strictness
getStrictness()

Returns the strictness of this writer.

public final boolean
isHtmlSafe()

Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.

public boolean
isLenient()

Returns true if the Strictness of this writer is equal to Strictness#LENIENT.

public JsonWriter

Returns:

this writer.
jsonValue
(String
the literal string value, or null to encode a null literal.
value
)

Writes value directly to the writer without quoting or escaping.

public JsonWriter

Returns:

this writer.
name
(String
the name of the forthcoming value. May not be null.
name
)

Encodes the property name.

private void
public JsonWriter

Returns:

this writer.
nullValue
()

Encodes null.

private JsonWriter
openScope(int empty, char openBracket)

Enters a new scope by appending any necessary whitespace and the given bracket.

private int
peek()

Returns the value on the top of the stack.

private void
push(int newTop)

private void
replaceTop(int topOfStack)

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

public final void
setFormattingStyle(FormattingStyle
the formatting style to use, must not be null.
formattingStyle
)

Sets the formatting style to be used in the encoded document.

public final void
setHtmlSafe(boolean htmlSafe)

Configures this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.

public final void
setIndent(String
a string containing only whitespace.
indent
)

Sets the indentation string to be repeated for each level of indentation in the encoded document.

public final void
setLenient(boolean
whether this writer should be lenient. If true, the strictness is set to Strictness#LENIENT. If false, the strictness is set to Strictness#LEGACY_STRICT.
lenient
)
Deprecated Please use setStrictness(Strictness) instead.

Sets the strictness of this writer.

public final void
setSerializeNulls(boolean serializeNulls)

Sets whether object members are serialized when their value is null.

public final void
setStrictness(Strictness
the new strictness of this writer. May not be null.
strictness
)

Configures how strict this writer is with regard to the syntax rules specified in RFC 8259.

private void
string(String value)

public JsonWriter

Returns:

this writer.
value
(String
the literal string value, or null to encode a null literal.
value
)

Encodes value.

public JsonWriter

Returns:

this writer.
value
(boolean value)

Encodes value.

public JsonWriter

Returns:

this writer.
value
(Boolean value)

Encodes value.

public JsonWriter

Returns:

this writer.
value
(float
a finite value, or if lenient, also NaN or infinity.
value
)

Encodes value.

public JsonWriter

Returns:

this writer.
value
(double
a finite value, or if lenient, also NaN or infinity.
value
)

Encodes value.

public JsonWriter

Returns:

this writer.
value
(long value)

Encodes value.

public JsonWriter

Returns:

this writer.
value
(Number
a finite value, or if lenient, also NaN or infinity.
value
)

Encodes value.

private void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

deferredNameback to summary
private String deferredName
formattedColonback to summary
private String formattedColon
formattedCommaback to summary
private String formattedComma
formattingStyleback to summary
private FormattingStyle formattingStyle
HTML_SAFE_REPLACEMENT_CHARSback to summary
private static final String[] HTML_SAFE_REPLACEMENT_CHARS
htmlSafeback to summary
private boolean htmlSafe
outback to summary
private final Writer out

The JSON output destination

REPLACEMENT_CHARSback to summary
private static final String[] REPLACEMENT_CHARS
serializeNullsback to summary
private boolean serializeNulls
stackback to summary
private int[] stack
stackSizeback to summary
private int stackSize
strictnessback to summary
private Strictness strictness
usesEmptyNewlineAndIndentback to summary
private boolean usesEmptyNewlineAndIndent
VALID_JSON_NUMBER_PATTERNback to summary
private static final Pattern VALID_JSON_NUMBER_PATTERN

Constructor Detail

JsonWriterback to summary
public JsonWriter(Writer out)

Creates a new instance that writes a JSON-encoded stream to out. For best performance, ensure Writer is buffered; wrapping in BufferedWriter if necessary.

Method Detail

alwaysCreatesValidJsonNumberback to summary
private static boolean alwaysCreatesValidJsonNumber(Class<? extends Number> c)

Returns whether the toString() of c will always return a valid JSON number.

beforeNameback to summary
private void beforeName() throws IOException

Inserts any necessary separators and whitespace before a name. Also adjusts the stack to expect the name's value.

beforeValueback to summary
private void beforeValue() throws IOException

Inserts any necessary separators and whitespace before a literal value, inline array, or inline object. Also adjusts the stack to expect either a closing bracket or another element.

Annotations
@SuppressWarnings:fallthrough
beginArrayback to summary
public JsonWriter beginArray() throws IOException

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

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
beginObjectback to summary
public JsonWriter beginObject() throws IOException

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

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
closeback to summary
public void close() throws IOException

Implements java.io.Closeable.close.

Flushes and closes this writer and the underlying Writer.

Annotations
@Override
Exceptions
IOException:
if the JSON document is incomplete.
closeScopeback to summary
private JsonWriter closeScope(int empty, int nonempty, char closeBracket) throws IOException

Closes the current scope by appending any necessary whitespace and the given bracket.

Annotations
@CanIgnoreReturnValue
endArrayback to summary
public JsonWriter endArray() throws IOException

Ends encoding the current array.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
endObjectback to summary
public JsonWriter endObject() throws IOException

Ends encoding the current object.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
flushback to summary
public void flush() throws IOException

Implements java.io.Flushable.flush.

Ensures all buffered data is written to the underlying Writer and flushes that writer.

Annotations
@Override
Exceptions
IOException:

Doc from java.io.Flushable.flush.

If an I/O error occurs

getFormattingStyleback to summary
public final FormattingStyle getFormattingStyle()

Returns the pretty printing style used by this writer.

Returns:FormattingStyle

the FormattingStyle that will be used.

Since
2.11.0
See Also
setFormattingStyle(FormattingStyle)
getSerializeNullsback to summary
public final boolean getSerializeNulls()

Returns true if object members are serialized when their value is null. This has no impact on array elements. The default is true.

See Also
setSerializeNulls(boolean)
getStrictnessback to summary
public final Strictness getStrictness()

Returns the strictness of this writer.

Since
2.11.0
See Also
setStrictness(Strictness)
isHtmlSafeback to summary
public final boolean isHtmlSafe()

Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.

See Also
setHtmlSafe(boolean)
isLenientback to summary
public boolean isLenient()

Returns true if the Strictness of this writer is equal to Strictness#LENIENT.

See Also
getStrictness()
jsonValueback to summary
public JsonWriter jsonValue(String value) throws IOException

Writes value directly to the writer without quoting or escaping. This might not be supported by all implementations, if not supported an UnsupportedOperationException is thrown.

Parameters
value:String

the literal string value, or null to encode a null literal.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
Exceptions
UnsupportedOperationException:
if this writer does not support writing raw JSON values.
Since
2.4
nameback to summary
public JsonWriter name(String name) throws IOException

Encodes the property name.

Parameters
name:String

the name of the forthcoming value. May not be null.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
newlineback to summary
private void newline() throws IOException
nullValueback to summary
public JsonWriter nullValue() throws IOException

Encodes null.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
openScopeback to summary
private JsonWriter openScope(int empty, char openBracket) throws IOException

Enters a new scope by appending any necessary whitespace and the given bracket.

Annotations
@CanIgnoreReturnValue
peekback to summary
private int peek()

Returns the value on the top of the stack.

pushback to summary
private void push(int newTop)
replaceTopback to summary
private void replaceTop(int topOfStack)

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

setFormattingStyleback to summary
public final void setFormattingStyle(FormattingStyle formattingStyle)

Sets the formatting style to be used in the encoded document.

The formatting style specifies for example the indentation string to be repeated for each level of indentation, or the newline style, to accommodate various OS styles.

Parameters
formattingStyle:FormattingStyle

the formatting style to use, must not be null.

Since
2.11.0
See Also
getFormattingStyle()
setHtmlSafeback to summary
public final void setHtmlSafe(boolean htmlSafe)

Configures this writer to emit JSON that's safe for direct inclusion in HTML and XML documents. This escapes the HTML characters <, >, &, = and ' before writing them to the stream. Without this setting, your XML/HTML encoder should replace these characters with the corresponding escape sequences.

See Also
isHtmlSafe()
setIndentback to summary
public final void setIndent(String indent)

Sets the indentation string to be repeated for each level of indentation in the encoded document. If indent.isEmpty() the encoded document will be compact. Otherwise the encoded document will be more human-readable.

This is a convenience method which overwrites any previously set formatting style with either FormattingStyle#COMPACT if the given indent string is empty, or FormattingStyle#PRETTY with the given indent if not empty.

Parameters
indent:String

a string containing only whitespace.

setLenientback to summary
public final void setLenient(boolean lenient)

Deprecated

Please use setStrictness(Strictness) instead. JsonWriter.setLenient(true) should be replaced by JsonWriter.setStrictness(Strictness.LENIENT) and JsonWriter.setLenient(false) should be replaced by JsonWriter.setStrictness(Strictness.LEGACY_STRICT).
However, if you used setLenient(false) before, you might prefer Strictness#STRICT now instead.

Sets the strictness of this writer.

Parameters
lenient:boolean

whether this writer should be lenient. If true, the strictness is set to Strictness#LENIENT. If false, the strictness is set to Strictness#LEGACY_STRICT.

Annotations
@Deprecated
@SuppressWarnings:InlineMeSuggester
See Also
setStrictness(Strictness)
setSerializeNullsback to summary
public final void setSerializeNulls(boolean serializeNulls)

Sets whether object members are serialized when their value is null. This has no impact on array elements. The default is true.

See Also
getSerializeNulls()
setStrictnessback to summary
public final void setStrictness(Strictness strictness)

Configures how strict this writer is with regard to the syntax rules specified in RFC 8259. By default, Strictness#LEGACY_STRICT is used.

Strictness#STRICT & Strictness#LEGACY_STRICT
The behavior of these is currently identical. In these strictness modes, the writer only writes JSON in accordance with RFC 8259.
Strictness#LENIENT
This mode relaxes the behavior of the writer to allow the writing of NaNs and infinities. It also allows writing multiple top level values.
Parameters
strictness:Strictness

the new strictness of this writer. May not be null.

Since
2.11.0
See Also
getStrictness()
stringback to summary
private void string(String value) throws IOException
valueback to summary
public JsonWriter value(String value) throws IOException

Encodes value.

Parameters
value:String

the literal string value, or null to encode a null literal.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
valueback to summary
public JsonWriter value(boolean value) throws IOException

Encodes value.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
valueback to summary
public JsonWriter value(Boolean value) throws IOException

Encodes value.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
Since
2.7
valueback to summary
public JsonWriter value(float value) throws IOException

Encodes value.

Parameters
value:float

a finite value, or if lenient, also NaN or infinity.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
Exceptions
IllegalArgumentException:
if the value is NaN or Infinity and this writer is not lenient.
Since
2.9.1
valueback to summary
public JsonWriter value(double value) throws IOException

Encodes value.

Parameters
value:double

a finite value, or if lenient, also NaN or infinity.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
Exceptions
IllegalArgumentException:
if the value is NaN or Infinity and this writer is not lenient.
valueback to summary
public JsonWriter value(long value) throws IOException

Encodes value.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
valueback to summary
public JsonWriter value(Number value) throws IOException

Encodes value. The value is written by directly writing the Number#toString() result to JSON. Implementations must make sure that the result represents a valid JSON number.

Parameters
value:Number

a finite value, or if lenient, also NaN or infinity.

Returns:JsonWriter

this writer.

Annotations
@CanIgnoreReturnValue
Exceptions
IllegalArgumentException:
if the value is NaN or Infinity and this writer is not lenient; or if the toString() result is not a valid JSON number.
writeDeferredNameback to summary
private void writeDeferredName() throws IOException