Package com.dslplatform.json
Class JsonWriter
- java.lang.Object
-
- com.dslplatform.json.JsonWriter
-
public final class JsonWriter extends java.lang.ObjectDslJson writes JSON into JsonWriter which has two primary modes of operation: * targeting specific output stream * buffering the entire response in memory In both cases JsonWriter writes into an byte[] buffer. If stream is used as target, it will copy buffer into the stream whenever there is no more room in buffer for new data. If stream is not used as target, it will grow the buffer to hold the encoded result. To use stream as target reset(OutputStream) must be called before processing. This class provides low level methods for JSON serialization.After the processing is done, in case then stream was used as target, flush() must be called to copy the remaining of the buffer into stream. When entire response was buffered in memory, buffer can be copied to stream or resulting byte[] can be used directly.
For maximum performance JsonWriter instances should be reused (to avoid allocation of new byte[] buffer instances). They should not be shared across threads (concurrently) so for Thread reuse it's best to use patterns such as ThreadLocal.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceJsonWriter.WriteObject<T>Custom objects can be serialized based on the implementation specified through this interface.
-
Field Summary
Fields Modifier and Type Field Description static byteARRAY_ENDHelper for writing JSON array end: ]static byteARRAY_STARTHelper for writing JSON array start: [private byte[]bufferstatic byteCOMMAHelper for writing comma separator: ,private Grisu3.FastDtoaBuilderdoubleBuilderstatic byteESCAPEHelper for writing JSON escape: \\private longflushedstatic byteOBJECT_ENDHelper for writing JSON object end: }static byteOBJECT_STARTHelper for writing JSON object start: {private intpositionstatic byteQUOTEHelper for writing JSON quote: "static byteSEMIHelper for writing semicolon: :private java.io.OutputStreamtargetprivate UnknownSerializerunknownSerializer
-
Constructor Summary
Constructors Constructor Description JsonWriter(byte[] buffer, UnknownSerializer unknownSerializer)JsonWriter(int size, UnknownSerializer unknownSerializer)JsonWriter(UnknownSerializer unknownSerializer)
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description (package private) voidadvance(int size)voidclose()Deprecated.private voidenlargeOrFlush(int size, int padding)(package private) byte[]ensureCapacity(int free)voidflush()If stream was used, copies the buffer to stream and resets the position in buffer to 0.longflushed()Total bytes currently flushed to streambyte[]getByteBuffer()Current buffer.voidreset()Resets the writer - same as calling reset(OutputStream = null)voidreset(java.io.OutputStream stream)Resets the writer - specifies the target stream and sets the position in buffer to 0.<T> voidserialize(java.util.Collection<T> collection, JsonWriter.WriteObject<T> encoder)Convenience method for serializing collection through instance serializer (WriteObject).<T extends JsonObject>
voidserialize(java.util.List<T> list)Convenience method for serializing list of JsonObject's.<T> voidserialize(java.util.List<T> list, JsonWriter.WriteObject<T> encoder)Convenience method for serializing list through instance serializer (WriteObject).<K,V>
voidserialize(java.util.Map<K,V> map, JsonWriter.WriteObject<K> keyEncoder, JsonWriter.WriteObject<V> valueEncoder)<T extends JsonObject>
voidserialize(T[] array)Convenience method for serializing array of JsonObject's.<T extends JsonObject>
voidserialize(T[] array, int len)Convenience method for serializing only part of JsonObject's array.<T> voidserialize(T[] array, JsonWriter.WriteObject<T> encoder)Convenience method for serializing array through instance serializer (WriteObject).voidserializeObject(java.lang.Object value)Generic object serializer which is used for "unknown schema" objects.voidserializeRaw(java.util.Collection collection, JsonWriter.WriteObject encoder)voidserializeRaw(java.util.List list, JsonWriter.WriteObject encoder)voidserializeRaw(java.util.Map map, JsonWriter.WriteObject keyEncoder, JsonWriter.WriteObject valueEncoder)intsize()Current position in the buffer.byte[]toByteArray()Content of buffer can be copied to another array of appropriate size.voidtoStream(java.io.OutputStream stream)When JsonWriter does not target stream, this method should be used to copy content of the buffer into target stream.java.lang.StringtoString()voidwriteAscii(byte[] buf)Copy bytes into JSON as is.voidwriteAscii(byte[] buf, int len)Copy part of byte buffer into JSON as is.voidwriteAscii(java.lang.String value)Write string consisting of only ascii characters.voidwriteAscii(java.lang.String value, int len)Write part of string consisting of only ascii characters.voidwriteBinary(byte[] value)Encode bytes as Base 64.voidwriteByte(byte value)Write a single byte into the JSON.(package private) voidwriteDouble(double value)voidwriteNull()Optimized method for writing 'null' into the JSON.<T> voidwriteQuoted(JsonWriter.WriteObject<T> keyWriter, T key)private voidwriteQuotedString(java.lang.CharSequence str, int i, int cur, int len)voidwriteRaw(byte[] buf, int offset, int len)Copy part of byte buffer into JSON as is.voidwriteString(java.lang.CharSequence value)Write a quoted string into the JSON.voidwriteString(java.lang.String value)Write a quoted string into the JSON.
-
-
-
Field Detail
-
position
private int position
-
flushed
private long flushed
-
target
private java.io.OutputStream target
-
buffer
private byte[] buffer
-
unknownSerializer
private final UnknownSerializer unknownSerializer
-
doubleBuilder
private final Grisu3.FastDtoaBuilder doubleBuilder
-
OBJECT_START
public static final byte OBJECT_START
Helper for writing JSON object start: {- See Also:
- Constant Field Values
-
OBJECT_END
public static final byte OBJECT_END
Helper for writing JSON object end: }- See Also:
- Constant Field Values
-
ARRAY_START
public static final byte ARRAY_START
Helper for writing JSON array start: [- See Also:
- Constant Field Values
-
ARRAY_END
public static final byte ARRAY_END
Helper for writing JSON array end: ]- See Also:
- Constant Field Values
-
COMMA
public static final byte COMMA
Helper for writing comma separator: ,- See Also:
- Constant Field Values
-
SEMI
public static final byte SEMI
Helper for writing semicolon: :- See Also:
- Constant Field Values
-
QUOTE
public static final byte QUOTE
Helper for writing JSON quote: "- See Also:
- Constant Field Values
-
ESCAPE
public static final byte ESCAPE
Helper for writing JSON escape: \\- See Also:
- Constant Field Values
-
-
Constructor Detail
-
JsonWriter
JsonWriter(@Nullable UnknownSerializer unknownSerializer)
-
JsonWriter
JsonWriter(int size, @Nullable UnknownSerializer unknownSerializer)
-
JsonWriter
JsonWriter(byte[] buffer, @Nullable UnknownSerializer unknownSerializer)
-
-
Method Detail
-
ensureCapacity
final byte[] ensureCapacity(int free)
-
advance
void advance(int size)
-
enlargeOrFlush
private void enlargeOrFlush(int size, int padding)
-
writeNull
public final void writeNull()
Optimized method for writing 'null' into the JSON.
-
writeByte
public final void writeByte(byte value)
Write a single byte into the JSON.- Parameters:
value- byte to write into the JSON
-
writeString
public final void writeString(java.lang.String value)
Write a quoted string into the JSON. String will be appropriately escaped according to JSON escaping rules.- Parameters:
value- string to write
-
writeString
public final void writeString(java.lang.CharSequence value)
Write a quoted string into the JSON. Char sequence will be appropriately escaped according to JSON escaping rules.- Parameters:
value- char sequence to write
-
writeQuotedString
private void writeQuotedString(java.lang.CharSequence str, int i, int cur, int len)
-
writeAscii
public final void writeAscii(java.lang.String value)
Write string consisting of only ascii characters. String will not be escaped according to JSON escaping rules.- Parameters:
value- ascii string
-
writeAscii
public final void writeAscii(java.lang.String value, int len)Write part of string consisting of only ascii characters. String will not be escaped according to JSON escaping rules.- Parameters:
value- ascii stringlen- part of the provided string to use
-
writeAscii
public final void writeAscii(byte[] buf)
Copy bytes into JSON as is. Provided buffer can't be null.- Parameters:
buf- byte buffer to copy
-
writeAscii
public final void writeAscii(byte[] buf, int len)Copy part of byte buffer into JSON as is. Provided buffer can't be null.- Parameters:
buf- byte buffer to copylen- part of buffer to copy
-
writeRaw
public final void writeRaw(byte[] buf, int offset, int len)Copy part of byte buffer into JSON as is. Provided buffer can't be null.- Parameters:
buf- byte buffer to copyoffset- in buffer to start fromlen- part of buffer to copy
-
writeBinary
public final void writeBinary(byte[] value)
Encode bytes as Base 64. Provided value can't be null.- Parameters:
value- bytes to encode
-
writeDouble
final void writeDouble(double value)
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
toByteArray
public final byte[] toByteArray()
Content of buffer can be copied to another array of appropriate size. This method can't be used when targeting output stream. Ideally it should be avoided if possible, since it will create an array copy. It's better to use getByteBuffer and size instead.- Returns:
- copy of the buffer up to the current position
-
toStream
public final void toStream(java.io.OutputStream stream) throws java.io.IOExceptionWhen JsonWriter does not target stream, this method should be used to copy content of the buffer into target stream. It will also reset the buffer position to 0 so writer can be continued to be used even without a call to reset().- Parameters:
stream- target stream- Throws:
java.io.IOException- propagates from stream.write
-
getByteBuffer
public final byte[] getByteBuffer()
Current buffer. If buffer grows, a new instance will be created and old one will not be used anymore.- Returns:
- current buffer
-
size
public final int size()
Current position in the buffer. When stream is not used, this is also equivalent to the size of the resulting JSON in bytes- Returns:
- position in the populated buffer
-
flushed
public final long flushed()
Total bytes currently flushed to stream- Returns:
- bytes flushed
-
reset
public final void reset()
Resets the writer - same as calling reset(OutputStream = null)
-
reset
public final void reset(@Nullable java.io.OutputStream stream)
Resets the writer - specifies the target stream and sets the position in buffer to 0. If stream is set to null, JsonWriter will work in growing byte[] buffer mode (entire response will be buffered in memory).- Parameters:
stream- sets/clears the target stream
-
flush
public final void flush()
If stream was used, copies the buffer to stream and resets the position in buffer to 0. It will not reset the stream as target, meaning new usages of the JsonWriter will try to use the already provided stream. It will not do anything if stream was not usedTo reset the stream to null use reset() or reset(OutputStream) methods.
-
close
@Deprecated public void close() throws java.io.IOExceptionDeprecated.This is deprecated method which exists only for backward compatibility- Throws:
java.io.IOException- unable to write to target stream
-
serialize
public <T extends JsonObject> void serialize(T[] array)
Convenience method for serializing array of JsonObject's. Array can't be null nor can't contain null values (it will result in NullPointerException).- Type Parameters:
T- type of objects- Parameters:
array- input objects
-
serialize
public <T extends JsonObject> void serialize(T[] array, int len)
Convenience method for serializing only part of JsonObject's array. Useful when array is reused and only part of it needs to be serialized. Array can't be null nor can't contain null values (it will result in NullPointerException).- Type Parameters:
T- type of objects- Parameters:
array- input objectslen- size of array which should be serialized
-
serialize
public <T extends JsonObject> void serialize(java.util.List<T> list)
Convenience method for serializing list of JsonObject's. List can't be null nor can't contain null values (it will result in NullPointerException). It will use list .get(index) method to access the object. When using .get(index) is not appropriate, it's better to call the serialize(Collection<JsonObject>) method instead.- Type Parameters:
T- type of objects- Parameters:
list- input objects
-
serialize
public <T> void serialize(@Nullable T[] array, JsonWriter.WriteObject<T> encoder)
Convenience method for serializing array through instance serializer (WriteObject). Array can be null and can contain null values. Instance serializer will not be invoked for null values- Type Parameters:
T- type of object- Parameters:
array- array to serializeencoder- instance serializer
-
serialize
public <T> void serialize(@Nullable java.util.List<T> list, JsonWriter.WriteObject<T> encoder)
Convenience method for serializing list through instance serializer (WriteObject). List can be null and can contain null values. Instance serializer will not be invoked for null values It will use list .get(index) method to access the object. When using .get(index) is not appropriate, it's better to call the serialize(Collection<JsonObject>, WriteObject) method instead.- Type Parameters:
T- type of object- Parameters:
list- list to serializeencoder- instance serializer
-
serializeRaw
public void serializeRaw(@Nullable java.util.List list, JsonWriter.WriteObject encoder)
-
serialize
public <T> void serialize(@Nullable java.util.Collection<T> collection, JsonWriter.WriteObject<T> encoder)
Convenience method for serializing collection through instance serializer (WriteObject). Collection can be null and can contain null values. Instance serializer will not be invoked for null values- Type Parameters:
T- type of object- Parameters:
collection- collection to serializeencoder- instance serializer
-
serializeRaw
public void serializeRaw(@Nullable java.util.Collection collection, JsonWriter.WriteObject encoder)
-
serialize
public <K,V> void serialize(@Nullable java.util.Map<K,V> map, JsonWriter.WriteObject<K> keyEncoder, JsonWriter.WriteObject<V> valueEncoder)
-
serializeRaw
public void serializeRaw(@Nullable java.util.Map map, JsonWriter.WriteObject keyEncoder, JsonWriter.WriteObject valueEncoder)
-
writeQuoted
public <T> void writeQuoted(JsonWriter.WriteObject<T> keyWriter, T key)
-
serializeObject
public void serializeObject(@Nullable java.lang.Object value)
Generic object serializer which is used for "unknown schema" objects. It will throw SerializationException in case if it doesn't know how to serialize provided instance. Will delegate the serialization to UnknownSerializer, which in most cases is the DslJson instance from which the writer was created. This enables it to use DslJson configuration and serialize using custom serializers (when they are provided).- Parameters:
value- instance to serialize
-
-