java.lang.Object
com.google.gson.stream.JsonWriter
- All Implemented Interfaces:
Closeable
,Flushable
,AutoCloseable
- Direct Known Subclasses:
JsonTreeWriter
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 newJsonWriter
. 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 appropriatevalue(java.lang.String)
methods or by nesting other arrays and objects. Finally close the array usingendArray()
. - To write objects, first call
beginObject()
. Write each of the object's properties by alternating calls toname(java.lang.String)
with the property's value. Write property values with the appropriatevalue(java.lang.String)
method or by nesting other objects or arrays. Finally close the object usingendObject()
.
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
.
- Since:
- 1.6
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate String
private static final String[]
private boolean
private String
A string containing a full set of spaces for a single level of indentation, or null for no pretty printing.private boolean
private final Writer
The output data, containing at most one top-level array or object.private static final String[]
private String
The name/value separator; either ":" or ": ".private boolean
private int[]
private int
private static final Pattern
-
Constructor Summary
ConstructorsConstructorDescriptionJsonWriter
(Writer out) Creates a new instance that writes a JSON-encoded stream toout
. -
Method Summary
Modifier and TypeMethodDescriptionprivate void
Inserts any necessary separators and whitespace before a name.private void
Inserts any necessary separators and whitespace before a literal value, inline array, or inline object.Begins encoding a new array.Begins encoding a new object.void
close()
Flushes and closes this writer and the underlyingWriter
.private JsonWriter
close
(int empty, int nonempty, char closeBracket) Closes the current scope by appending any necessary whitespace and the given bracket.endArray()
Ends encoding the current array.Ends encoding the current object.void
flush()
Ensures all buffered data is written to the underlyingWriter
and flushes that writer.final boolean
Returns true if object members are serialized when their value is null.final boolean
Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.boolean
Returns true if this writer has relaxed syntax rules.private static boolean
isTrustedNumberType
(Class<? extends Number> c) Returns whether thetoString()
ofc
can be trusted to return a valid JSON number.Writesvalue
directly to the writer without quoting or escaping.Encodes the property name.private void
newline()
Encodesnull
.private JsonWriter
open
(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.final void
setHtmlSafe
(boolean htmlSafe) Configure this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.final void
Sets the indentation string to be repeated for each level of indentation in the encoded document.final void
setLenient
(boolean lenient) Configure this writer to relax its syntax rules.final void
setSerializeNulls
(boolean serializeNulls) Sets whether object members are serialized when their value is null.private void
value
(boolean value) Encodesvalue
.value
(double value) Encodesvalue
.value
(float value) Encodesvalue
.value
(long value) Encodesvalue
.Encodesvalue
.Encodesvalue
.Encodesvalue
.private void
-
Field Details
-
VALID_JSON_NUMBER_PATTERN
-
REPLACEMENT_CHARS
-
HTML_SAFE_REPLACEMENT_CHARS
-
out
The output data, containing at most one top-level array or object. -
stack
private int[] stack -
stackSize
private int stackSize -
indent
A string containing a full set of spaces for a single level of indentation, or null for no pretty printing. -
separator
The name/value separator; either ":" or ": ". -
lenient
private boolean lenient -
htmlSafe
private boolean htmlSafe -
deferredName
-
serializeNulls
private boolean serializeNulls
-
-
Constructor Details
-
JsonWriter
Creates a new instance that writes a JSON-encoded stream toout
. For best performance, ensureWriter
is buffered; wrapping inBufferedWriter
if necessary.
-
-
Method Details
-
setIndent
Sets the indentation string to be repeated for each level of indentation in the encoded document. Ifindent.isEmpty()
the encoded document will be compact. Otherwise the encoded document will be more human-readable.- Parameters:
indent
- a string containing only whitespace.
-
setLenient
public final void setLenient(boolean lenient) Configure this writer to relax its syntax rules. By default, this writer only emits well-formed JSON as specified by RFC 7159. Setting the writer to lenient permits the following:- Top-level values of any type. With strict writing, the top-level value must be an object or an array.
- Numbers may be
NaNs
orinfinities
.
-
isLenient
public boolean isLenient()Returns true if this writer has relaxed syntax rules. -
setHtmlSafe
public final void setHtmlSafe(boolean htmlSafe) Configure 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. -
isHtmlSafe
public final boolean isHtmlSafe()Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents. -
setSerializeNulls
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. -
getSerializeNulls
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. -
beginArray
Begins encoding a new array. Each call to this method must be paired with a call toendArray()
.- Returns:
- this writer.
- Throws:
IOException
-
endArray
Ends encoding the current array.- Returns:
- this writer.
- Throws:
IOException
-
beginObject
Begins encoding a new object. Each call to this method must be paired with a call toendObject()
.- Returns:
- this writer.
- Throws:
IOException
-
endObject
Ends encoding the current object.- Returns:
- this writer.
- Throws:
IOException
-
open
Enters a new scope by appending any necessary whitespace and the given bracket.- Throws:
IOException
-
close
Closes the current scope by appending any necessary whitespace and the given bracket.- Throws:
IOException
-
push
private void push(int newTop) -
peek
private int peek()Returns the value on the top of the stack. -
replaceTop
private void replaceTop(int topOfStack) Replace the value on the top of the stack with the given value. -
name
Encodes the property name.- Parameters:
name
- the name of the forthcoming value. May not be null.- Returns:
- this writer.
- Throws:
IOException
-
writeDeferredName
- Throws:
IOException
-
value
Encodesvalue
.- Parameters:
value
- the literal string value, or null to encode a null literal.- Returns:
- this writer.
- Throws:
IOException
-
jsonValue
Writesvalue
directly to the writer without quoting or escaping.- Parameters:
value
- the literal string value, or null to encode a null literal.- Returns:
- this writer.
- Throws:
IOException
-
nullValue
Encodesnull
.- Returns:
- this writer.
- Throws:
IOException
-
value
Encodesvalue
.- Returns:
- this writer.
- Throws:
IOException
-
value
Encodesvalue
.- Returns:
- this writer.
- Throws:
IOException
-
value
Encodesvalue
.- Parameters:
value
- a finite value, or iflenient
, alsoNaN
orinfinity
.- Returns:
- this writer.
- Throws:
IllegalArgumentException
- if the value is NaN or Infinity and this writer is notlenient
.IOException
-
value
Encodesvalue
.- Parameters:
value
- a finite value, or iflenient
, alsoNaN
orinfinity
.- Returns:
- this writer.
- Throws:
IllegalArgumentException
- if the value is NaN or Infinity and this writer is notlenient
.IOException
-
value
Encodesvalue
.- Returns:
- this writer.
- Throws:
IOException
-
isTrustedNumberType
Returns whether thetoString()
ofc
can be trusted to return a valid JSON number. -
value
Encodesvalue
. The value is written by directly writing theObject.toString()
result to JSON. Implementations must make sure that the result represents a valid JSON number.- Parameters:
value
- a finite value, or iflenient
, alsoNaN
orinfinity
.- Returns:
- this writer.
- Throws:
IllegalArgumentException
- if the value is NaN or Infinity and this writer is notlenient
; or if thetoString()
result is not a valid JSON number.IOException
-
flush
Ensures all buffered data is written to the underlyingWriter
and flushes that writer.- Specified by:
flush
in interfaceFlushable
- Throws:
IOException
-
close
Flushes and closes this writer and the underlyingWriter
.- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceCloseable
- Throws:
IOException
- if the JSON document is incomplete.
-
string
- Throws:
IOException
-
newline
- Throws:
IOException
-
beforeName
Inserts any necessary separators and whitespace before a name. Also adjusts the stack to expect the name's value.- Throws:
IOException
-
beforeValue
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.- Throws:
IOException
-