- java.lang.Object
-
- com.google.gson.stream.JsonWriter
-
- All Implemented Interfaces:
Closeable,Flushable,AutoCloseable
public class JsonWriter extends Object implements Closeable, Flushable
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 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().
Configuration
The behavior of this writer can be customized with the following methods:setFormattingStyle(FormattingStyle), the default isFormattingStyle.COMPACTsetHtmlSafe(boolean), by default HTML characters are not escaped in the JSON outputsetStrictness(Strictness), the default isStrictness.LEGACY_STRICTsetSerializeNulls(boolean), by defaultnullis serialized
JsonWriterinstances used internally by theGsonclass differs, and can be adjusted with the variousGsonBuildermethods.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
- Author:
- Jesse Wilson
-
-
Constructor Summary
Constructors Constructor Description JsonWriter(Writer out)Creates a new instance that writes a JSON-encoded stream toout.
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description JsonWriterbeginArray()Begins encoding a new array.JsonWriterbeginObject()Begins encoding a new object.voidclose()Flushes and closes this writer and the underlyingWriter.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.FormattingStylegetFormattingStyle()Returns the pretty printing style used by this writer.booleangetSerializeNulls()Returns true if object members are serialized when their value is null.StrictnessgetStrictness()Returns the strictness of this writer.booleanisHtmlSafe()Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.booleanisLenient()Returns true if theStrictnessof this writer is equal toStrictness.LENIENT.JsonWriterjsonValue(String value)Writesvaluedirectly to the writer without quoting or escaping.JsonWritername(String name)Encodes the property name.JsonWriternullValue()Encodesnull.voidsetFormattingStyle(FormattingStyle formattingStyle)Sets the formatting style to be used in the encoded document.voidsetHtmlSafe(boolean htmlSafe)Configures this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.voidsetIndent(String indent)Sets the indentation string to be repeated for each level of indentation in the encoded document.voidsetLenient(boolean lenient)Deprecated.Please usesetStrictness(Strictness)instead.voidsetSerializeNulls(boolean serializeNulls)Sets whether object members are serialized when their value is null.voidsetStrictness(Strictness strictness)Configures how strict this writer is with regard to the syntax rules specified in RFC 8259.JsonWritervalue(boolean value)Encodesvalue.JsonWritervalue(double value)Encodesvalue.JsonWritervalue(float value)Encodesvalue.JsonWritervalue(long value)Encodesvalue.JsonWritervalue(Boolean value)Encodesvalue.JsonWritervalue(Number value)Encodesvalue.JsonWritervalue(String value)Encodesvalue.
-
-
-
Constructor Detail
-
JsonWriter
public JsonWriter(Writer out)
Creates a new instance that writes a JSON-encoded stream toout. For best performance, ensureWriteris buffered; wrapping inBufferedWriterif necessary.
-
-
Method Detail
-
setIndent
public final void setIndent(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.This is a convenience method which overwrites any previously set formatting style with either
FormattingStyle.COMPACTif the given indent string is empty, orFormattingStyle.PRETTYwith the given indent if not empty.- Parameters:
indent- a string containing only whitespace.
-
setFormattingStyle
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- the formatting style to use, must not benull.- Since:
- 2.11.0
-
getFormattingStyle
public final FormattingStyle getFormattingStyle()
Returns the pretty printing style used by this writer.- Returns:
- the
FormattingStylethat will be used. - Since:
- 2.11.0
-
setLenient
@Deprecated public final void setLenient(boolean lenient)
Deprecated.Please usesetStrictness(Strictness)instead.JsonWriter.setLenient(true)should be replaced byJsonWriter.setStrictness(Strictness.LENIENT)andJsonWriter.setLenient(false)should be replaced byJsonWriter.setStrictness(Strictness.LEGACY_STRICT).
However, if you usedsetLenient(false)before, you might preferStrictness.STRICTnow instead.Sets the strictness of this writer.- Parameters:
lenient- whether this writer should be lenient. If true, the strictness is set toStrictness.LENIENT. If false, the strictness is set toStrictness.LEGACY_STRICT.- See Also:
setStrictness(Strictness)
-
isLenient
public boolean isLenient()
Returns true if theStrictnessof this writer is equal toStrictness.LENIENT.- See Also:
getStrictness()
-
setStrictness
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_STRICTis 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
NaNsandinfinities. It also allows writing multiple top level values.
- Parameters:
strictness- the new strictness of this writer. May not benull.- Since:
- 2.11.0
- See Also:
getStrictness()
-
getStrictness
public final Strictness getStrictness()
Returns the strictness of this writer.- Since:
- 2.11.0
- See Also:
setStrictness(Strictness)
-
setHtmlSafe
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.
-
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
@CanIgnoreReturnValue public JsonWriter beginArray() throws IOException
Begins encoding a new array. Each call to this method must be paired with a call toendArray().- Returns:
- this writer.
- Throws:
IOException
-
endArray
@CanIgnoreReturnValue public JsonWriter endArray() throws IOException
Ends encoding the current array.- Returns:
- this writer.
- Throws:
IOException
-
beginObject
@CanIgnoreReturnValue public JsonWriter beginObject() throws IOException
Begins encoding a new object. Each call to this method must be paired with a call toendObject().- Returns:
- this writer.
- Throws:
IOException
-
endObject
@CanIgnoreReturnValue public JsonWriter endObject() throws IOException
Ends encoding the current object.- Returns:
- this writer.
- Throws:
IOException
-
name
@CanIgnoreReturnValue public JsonWriter name(String name) throws IOException
Encodes the property name.- Parameters:
name- the name of the forthcoming value. May not benull.- Returns:
- this writer.
- Throws:
IOException
-
value
@CanIgnoreReturnValue public JsonWriter value(String value) throws IOException
Encodesvalue.- Parameters:
value- the literal string value, or null to encode a null literal.- Returns:
- this writer.
- Throws:
IOException
-
value
@CanIgnoreReturnValue public JsonWriter value(boolean value) throws IOException
Encodesvalue.- Returns:
- this writer.
- Throws:
IOException
-
value
@CanIgnoreReturnValue public JsonWriter value(Boolean value) throws IOException
Encodesvalue.- Returns:
- this writer.
- Throws:
IOException- Since:
- 2.7
-
value
@CanIgnoreReturnValue public JsonWriter value(float value) throws IOException
Encodesvalue.- Parameters:
value- a finite value, or iflenient, alsoNaNorinfinity.- Returns:
- this writer.
- Throws:
IllegalArgumentException- if the value is NaN or Infinity and this writer is notlenient.IOException- Since:
- 2.9.1
-
value
@CanIgnoreReturnValue public JsonWriter value(double value) throws IOException
Encodesvalue.- Parameters:
value- a finite value, or iflenient, alsoNaNorinfinity.- Returns:
- this writer.
- Throws:
IllegalArgumentException- if the value is NaN or Infinity and this writer is notlenient.IOException
-
value
@CanIgnoreReturnValue public JsonWriter value(long value) throws IOException
Encodesvalue.- Returns:
- this writer.
- Throws:
IOException
-
value
@CanIgnoreReturnValue public JsonWriter value(Number value) throws 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.- Parameters:
value- a finite value, or iflenient, alsoNaNorinfinity.- 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
-
nullValue
@CanIgnoreReturnValue public JsonWriter nullValue() throws IOException
Encodesnull.- Returns:
- this writer.
- Throws:
IOException
-
jsonValue
@CanIgnoreReturnValue public JsonWriter jsonValue(String value) throws 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:
UnsupportedOperationException- if this writer does not support writing raw JSON values.IOException- Since:
- 2.4
-
flush
public void flush() throws IOExceptionEnsures all buffered data is written to the underlyingWriterand flushes that writer.- Specified by:
flushin interfaceFlushable- Throws:
IOException
-
close
public void close() throws IOExceptionFlushes and closes this writer and the underlyingWriter.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException- if the JSON document is incomplete.
-
-