- java.lang.Object
-
- com.google.gson.stream.JsonWriter
-
- All Implemented Interfaces:
java.io.Closeable,java.io.Flushable,java.lang.AutoCloseable
- Direct Known Subclasses:
JsonTreeWriter
public class JsonWriter extends java.lang.Object implements java.io.Closeable, java.io.FlushableWrites 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. 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:
This code encodes the above structure:[ { "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 } } ]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
JsonWritermay 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 anIllegalStateException.- Since:
- 1.6
-
-
Field Summary
Fields Modifier and Type Field Description private java.lang.StringdeferredNameprivate static java.lang.String[]HTML_SAFE_REPLACEMENT_CHARSprivate booleanhtmlSafeprivate java.lang.StringindentA string containing a full set of spaces for a single level of indentation, or null for no pretty printing.private booleanlenientprivate java.io.WriteroutThe JSON output destinationprivate static java.lang.String[]REPLACEMENT_CHARSprivate java.lang.StringseparatorThe name/value separator; either ":" or ": ".private booleanserializeNullsprivate int[]stackprivate intstackSizeprivate static java.util.regex.PatternVALID_JSON_NUMBER_PATTERN
-
Constructor Summary
Constructors Constructor Description JsonWriter(java.io.Writer out)Creates a new instance that writes a JSON-encoded stream toout.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private voidbeforeName()Inserts any necessary separators and whitespace before a name.private voidbeforeValue()Inserts any necessary separators and whitespace before a literal value, inline array, or inline object.JsonWriterbeginArray()Begins encoding a new array.JsonWriterbeginObject()Begins encoding a new object.voidclose()Flushes and closes this writer and the underlyingWriter.private JsonWriterclose(int empty, int nonempty, char closeBracket)Closes the current scope by appending any necessary whitespace and the given bracket.JsonWriterendArray()Ends encoding the current array.JsonWriterendObject()Ends encoding the current object.voidflush()Ensures all buffered data is written to the underlyingWriterand flushes that writer.booleangetSerializeNulls()Returns true if object members are serialized when their value is null.booleanisHtmlSafe()Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.booleanisLenient()Returns true if this writer has relaxed syntax rules.private static booleanisTrustedNumberType(java.lang.Class<? extends java.lang.Number> c)Returns whether thetoString()ofccan be trusted to return a valid JSON number.JsonWriterjsonValue(java.lang.String value)Writesvaluedirectly to the writer without quoting or escaping.JsonWritername(java.lang.String name)Encodes the property name.private voidnewline()JsonWriternullValue()Encodesnull.private JsonWriteropen(int empty, char openBracket)Enters a new scope by appending any necessary whitespace and the given bracket.private intpeek()Returns the value on the top of the stack.private voidpush(int newTop)private voidreplaceTop(int topOfStack)Replace the value on the top of the stack with the given value.voidsetHtmlSafe(boolean htmlSafe)Configure this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.voidsetIndent(java.lang.String indent)Sets the indentation string to be repeated for each level of indentation in the encoded document.voidsetLenient(boolean lenient)Configure this writer to relax its syntax rules.voidsetSerializeNulls(boolean serializeNulls)Sets whether object members are serialized when their value is null.private voidstring(java.lang.String value)JsonWritervalue(boolean value)Encodesvalue.JsonWritervalue(double value)Encodesvalue.JsonWritervalue(float value)Encodesvalue.JsonWritervalue(long value)Encodesvalue.JsonWritervalue(java.lang.Boolean value)Encodesvalue.JsonWritervalue(java.lang.Number value)Encodesvalue.JsonWritervalue(java.lang.String value)Encodesvalue.private voidwriteDeferredName()
-
-
-
Field Detail
-
VALID_JSON_NUMBER_PATTERN
private static final java.util.regex.Pattern VALID_JSON_NUMBER_PATTERN
-
REPLACEMENT_CHARS
private static final java.lang.String[] REPLACEMENT_CHARS
-
HTML_SAFE_REPLACEMENT_CHARS
private static final java.lang.String[] HTML_SAFE_REPLACEMENT_CHARS
-
out
private final java.io.Writer out
The JSON output destination
-
stack
private int[] stack
-
stackSize
private int stackSize
-
indent
private java.lang.String indent
A string containing a full set of spaces for a single level of indentation, or null for no pretty printing.
-
separator
private java.lang.String separator
The name/value separator; either ":" or ": ".
-
lenient
private boolean lenient
-
htmlSafe
private boolean htmlSafe
-
deferredName
private java.lang.String deferredName
-
serializeNulls
private boolean serializeNulls
-
-
Method Detail
-
setIndent
public final void setIndent(java.lang.String indent)
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:- Numbers may be
NaNsorinfinities.
- Numbers may be
-
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
public JsonWriter beginArray() throws java.io.IOException
Begins encoding a new array. Each call to this method must be paired with a call toendArray().- Returns:
- this writer.
- Throws:
java.io.IOException
-
endArray
public JsonWriter endArray() throws java.io.IOException
Ends encoding the current array.- Returns:
- this writer.
- Throws:
java.io.IOException
-
beginObject
public JsonWriter beginObject() throws java.io.IOException
Begins encoding a new object. Each call to this method must be paired with a call toendObject().- Returns:
- this writer.
- Throws:
java.io.IOException
-
endObject
public JsonWriter endObject() throws java.io.IOException
Ends encoding the current object.- Returns:
- this writer.
- Throws:
java.io.IOException
-
open
private JsonWriter open(int empty, char openBracket) throws java.io.IOException
Enters a new scope by appending any necessary whitespace and the given bracket.- Throws:
java.io.IOException
-
close
private JsonWriter close(int empty, int nonempty, char closeBracket) throws java.io.IOException
Closes the current scope by appending any necessary whitespace and the given bracket.- Throws:
java.io.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
public JsonWriter name(java.lang.String name) throws java.io.IOException
Encodes the property name.- Parameters:
name- the name of the forthcoming value. May not be null.- Returns:
- this writer.
- Throws:
java.io.IOException
-
writeDeferredName
private void writeDeferredName() throws java.io.IOException- Throws:
java.io.IOException
-
value
public JsonWriter value(java.lang.String value) throws java.io.IOException
Encodesvalue.- Parameters:
value- the literal string value, or null to encode a null literal.- Returns:
- this writer.
- Throws:
java.io.IOException
-
jsonValue
public JsonWriter jsonValue(java.lang.String value) throws java.io.IOException
Writesvaluedirectly to the writer without quoting or escaping. This might not be supported by all implementations, if not supported anUnsupportedOperationExceptionis thrown.- Parameters:
value- the literal string value, or null to encode a null literal.- Returns:
- this writer.
- Throws:
java.lang.UnsupportedOperationException- if this writer does not support writing raw JSON values.java.io.IOException- Since:
- 2.4
-
nullValue
public JsonWriter nullValue() throws java.io.IOException
Encodesnull.- Returns:
- this writer.
- Throws:
java.io.IOException
-
value
public JsonWriter value(boolean value) throws java.io.IOException
Encodesvalue.- Returns:
- this writer.
- Throws:
java.io.IOException
-
value
public JsonWriter value(java.lang.Boolean value) throws java.io.IOException
Encodesvalue.- Returns:
- this writer.
- Throws:
java.io.IOException- Since:
- 2.7
-
value
public JsonWriter value(float value) throws java.io.IOException
Encodesvalue.
-
value
public JsonWriter value(double value) throws java.io.IOException
Encodesvalue.
-
value
public JsonWriter value(long value) throws java.io.IOException
Encodesvalue.- Returns:
- this writer.
- Throws:
java.io.IOException
-
isTrustedNumberType
private static boolean isTrustedNumberType(java.lang.Class<? extends java.lang.Number> c)
Returns whether thetoString()ofccan be trusted to return a valid JSON number.
-
value
public JsonWriter value(java.lang.Number value) throws java.io.IOException
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.
-
flush
public void flush() throws java.io.IOExceptionEnsures all buffered data is written to the underlyingWriterand flushes that writer.- Specified by:
flushin interfacejava.io.Flushable- Throws:
java.io.IOException
-
close
public void close() throws java.io.IOExceptionFlushes and closes this writer and the underlyingWriter.- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable- Throws:
java.io.IOException- if the JSON document is incomplete.
-
string
private void string(java.lang.String value) throws java.io.IOException- Throws:
java.io.IOException
-
newline
private void newline() throws java.io.IOException- Throws:
java.io.IOException
-
beforeName
private void beforeName() throws java.io.IOExceptionInserts any necessary separators and whitespace before a name. Also adjusts the stack to expect the name's value.- Throws:
java.io.IOException
-
beforeValue
private void beforeValue() throws java.io.IOExceptionInserts 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:
java.io.IOException
-
-