Class DefaultJsonWriter
java.lang.Object
org.dominokit.jacksonapt.stream.impl.DefaultJsonWriter
- All Implemented Interfaces:
JsonWriter
public class DefaultJsonWriter extends java.lang.Object implements JsonWriter
Writes a JSON (RFC 4627)
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) {
JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
writer.setIndentSpaces(4);
writeMessagesArray(writer, messages);
writer.close();
}
<p>
public void writeMessagesArray(JsonWriter writer, List<Message> messages) {
writer.beginArray();
for (Message message : messages) {
writeMessage(writer, message);
}
writer.endArray();
}
<p>
public void writeMessage(JsonWriter writer, Message message) {
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();
}
<p>
public void writeUser(JsonWriter writer, User user) {
writer.beginObject();
writer.name("name").value(user.getName());
writer.name("followers_count").value(user.getFollowersCount());
writer.endObject();
}
<p>
public void writeDoublesArray(JsonWriter writer, List<Double> doubles) {
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
- Version:
- $Id: $
- Author:
- Jesse Wilson
-
Constructor Summary
Constructors Constructor Description DefaultJsonWriter(java.lang.StringBuilder out)Creates a new instance that writes a JSON-encoded stream toout. -
Method Summary
Modifier and Type Method Description DefaultJsonWriterbeginArray()Begins encoding a new array.DefaultJsonWriterbeginObject()Begins encoding a new object.DefaultJsonWritercancelName()cancelNamevoidclose()Flushes and closes this writer and the underlyingStringBuilder.static java.lang.StringencodeString(java.lang.String value)encodeStringstatic voidencodeString(java.lang.String value, java.lang.StringBuilder out)encodeString.DefaultJsonWriterendArray()Ends encoding the current array.DefaultJsonWriterendObject()Ends encoding the current object.voidflush()Ensures all buffered data is written to the underlyingStringBuilderand flushes that writer.java.lang.StringgetOutput()getOutputbooleangetSerializeNulls()getSerializeNullsbooleanisLenient()Returns true if this writer has relaxed syntax rules.DefaultJsonWritername(java.lang.String name)Encodes the property name.DefaultJsonWriternullValue()Encodesnull.DefaultJsonWriterrawValue(java.lang.Object value)Encodesvalue.toString() as is.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.DefaultJsonWriterunescapeName(java.lang.String name)Encodes the property name without escaping it.DefaultJsonWriterunescapeValue(java.lang.String value)Encodesvaluewithout escaping it.DefaultJsonWritervalue(boolean value)Encodesvalue.DefaultJsonWritervalue(double value)Encodesvalue.DefaultJsonWritervalue(long value)Encodesvalue.DefaultJsonWritervalue(java.lang.Number value)Encodesvalue.DefaultJsonWritervalue(java.lang.String value)Encodesvalue.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Constructor Details
-
DefaultJsonWriter
public DefaultJsonWriter(java.lang.StringBuilder out)Creates a new instance that writes a JSON-encoded stream toout.- Parameters:
out- aStringBuilderobject.
-
-
Method Details
-
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.- Specified by:
setIndentin interfaceJsonWriter- 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 4627. 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
NaNsorinfinities.
- Specified by:
setLenientin interfaceJsonWriter- Parameters:
lenient- a boolean.
-
isLenient
public boolean isLenient()Returns true if this writer has relaxed syntax rules.- Returns:
- a boolean.
-
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.- Specified by:
setSerializeNullsin interfaceJsonWriter- Parameters:
serializeNulls- a boolean.
-
getSerializeNulls
public final boolean getSerializeNulls()getSerializeNulls
Returns true if object members are serialized when their value is null. This has no impact on array elements. The default is true.
- Specified by:
getSerializeNullsin interfaceJsonWriter- Returns:
- a boolean.
-
beginArray
Begins encoding a new array. Each call to this method must be paired with a call toJsonWriter.endArray().- Specified by:
beginArrayin interfaceJsonWriter- Returns:
- this writer.
-
endArray
Ends encoding the current array.- Specified by:
endArrayin interfaceJsonWriter- Returns:
- this writer.
-
beginObject
Begins encoding a new object. Each call to this method must be paired with a call toJsonWriter.endObject().- Specified by:
beginObjectin interfaceJsonWriter- Returns:
- this writer.
-
endObject
Ends encoding the current object.- Specified by:
endObjectin interfaceJsonWriter- Returns:
- this writer.
-
name
Encodes the property name.- Specified by:
namein interfaceJsonWriter- Parameters:
name- the name of the forthcoming value. May not be null.- Returns:
- this writer.
-
unescapeName
Encodes the property name without escaping it.- Specified by:
unescapeNamein interfaceJsonWriter- Parameters:
name- the name of the forthcoming value. May not be null.- Returns:
- this writer.
-
value
Encodesvalue.- Specified by:
valuein interfaceJsonWriter- Parameters:
value- the literal string value, or null to encode a null literal.- Returns:
- this writer.
-
unescapeValue
Encodesvaluewithout escaping it.- Specified by:
unescapeValuein interfaceJsonWriter- Parameters:
value- the literal string value, or null to encode a null literal.- Returns:
- this writer.
-
nullValue
Encodesnull.- Specified by:
nullValuein interfaceJsonWriter- Returns:
- this writer.
-
cancelName
cancelName
- Specified by:
cancelNamein interfaceJsonWriter- Returns:
- a
JsonWriterobject.
-
value
Encodesvalue.- Specified by:
valuein interfaceJsonWriter- Parameters:
value- a boolean.- Returns:
- this writer.
-
value
Encodesvalue.- Specified by:
valuein interfaceJsonWriter- Parameters:
value- a finite value. May not beNaNsorinfinities.- Returns:
- this writer.
-
value
Encodesvalue.- Specified by:
valuein interfaceJsonWriter- Parameters:
value- a long.- Returns:
- this writer.
-
value
Encodesvalue.- Specified by:
valuein interfaceJsonWriter- Parameters:
value- a finite value. May not beNaNsorinfinities.- Returns:
- this writer.
-
rawValue
Encodesvalue.toString() as is.- Specified by:
rawValuein interfaceJsonWriter- Parameters:
value- a value .- Returns:
- this writer.
-
flush
public void flush()Ensures all buffered data is written to the underlyingStringBuilderand flushes that writer.- Specified by:
flushin interfaceJsonWriter
-
close
public void close()Flushes and closes this writer and the underlyingStringBuilder.- Specified by:
closein interfaceJsonWriter
-
encodeString
public static void encodeString(java.lang.String value, java.lang.StringBuilder out)encodeString.
- Parameters:
value- aStringobject.out- aStringBuilderobject.
-
encodeString
public static java.lang.String encodeString(java.lang.String value)encodeString
- Parameters:
value- aStringobject.- Returns:
- a
Stringobject.
-
getOutput
public java.lang.String getOutput()getOutput
- Specified by:
getOutputin interfaceJsonWriter- Returns:
- the output when the serialization is over
-