Package com.dslplatform.json
Class JsonWriter
java.lang.Object
com.dslplatform.json.JsonWriter
DslJson 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 ClassesModifier and TypeClassDescriptionstatic interfaceCustom objects can be serialized based on the implementation specified through this interface. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final byteHelper for writing JSON array end: ]static final byteHelper for writing JSON array start: [private byte[]static final byteHelper for writing comma separator: ,private final Grisu3.FastDtoaBuilderstatic final byteHelper for writing JSON escape: \\private longstatic final byteHelper for writing JSON object end: }static final byteHelper for writing JSON object start: {private intstatic final byteHelper for writing JSON quote: "static final byteHelper for writing semicolon: :private OutputStreamprivate final UnknownSerializer -
Constructor Summary
ConstructorsConstructorDescriptionJsonWriter(byte[] buffer, UnknownSerializer unknownSerializer) JsonWriter(int size, UnknownSerializer unknownSerializer) JsonWriter(UnknownSerializer unknownSerializer) -
Method Summary
Modifier and TypeMethodDescription(package private) voidadvance(int size) voidclose()Deprecated.private voidenlargeOrFlush(int size, int padding) (package private) final byte[]ensureCapacity(int free) final voidflush()If stream was used, copies the buffer to stream and resets the position in buffer to 0.final longflushed()Total bytes currently flushed to streamfinal byte[]Current buffer.final voidreset()Resets the writer - same as calling reset(OutputStream = null)final voidreset(OutputStream stream) Resets the writer - specifies the target stream and sets the position in buffer to 0.<T> voidserialize(Collection<T> collection, JsonWriter.WriteObject<T> encoder) Convenience method for serializing collection through instance serializer (WriteObject).<T extends JsonObject>
voidConvenience method for serializing list of JsonObject's.<T> voidserialize(List<T> list, JsonWriter.WriteObject<T> encoder) Convenience method for serializing list through instance serializer (WriteObject).<K,V> void serialize(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(Object value) Generic object serializer which is used for "unknown schema" objects.voidserializeRaw(Collection collection, JsonWriter.WriteObject encoder) voidserializeRaw(List list, JsonWriter.WriteObject encoder) voidserializeRaw(Map map, JsonWriter.WriteObject keyEncoder, JsonWriter.WriteObject valueEncoder) final intsize()Current position in the buffer.final byte[]Content of buffer can be copied to another array of appropriate size.final voidtoStream(OutputStream stream) When JsonWriter does not target stream, this method should be used to copy content of the buffer into target stream.toString()final voidwriteAscii(byte[] buf) Copy bytes into JSON as is.final voidwriteAscii(byte[] buf, int len) Copy part of byte buffer into JSON as is.final voidwriteAscii(String value) Write string consisting of only ascii characters.final voidwriteAscii(String value, int len) Write part of string consisting of only ascii characters.final voidwriteBinary(byte[] value) Encode bytes as Base 64.final voidwriteByte(byte value) Write a single byte into the JSON.(package private) final voidwriteDouble(double value) final voidOptimized method for writing 'null' into the JSON.<T> voidwriteQuoted(JsonWriter.WriteObject<T> keyWriter, T key) private voidwriteQuotedString(CharSequence str, int i, int cur, int len) final voidwriteRaw(byte[] buf, int offset, int len) Copy part of byte buffer into JSON as is.final voidwriteString(CharSequence value) Write a quoted string into the JSON.final voidwriteString(String value) Write a quoted string into the JSON.
-
Field Details
-
position
private int position -
flushed
private long flushed -
target
-
buffer
private byte[] buffer -
unknownSerializer
-
doubleBuilder
-
OBJECT_START
public static final byte OBJECT_STARTHelper for writing JSON object start: {- See Also:
-
OBJECT_END
public static final byte OBJECT_ENDHelper for writing JSON object end: }- See Also:
-
ARRAY_START
public static final byte ARRAY_STARTHelper for writing JSON array start: [- See Also:
-
ARRAY_END
public static final byte ARRAY_ENDHelper for writing JSON array end: ]- See Also:
-
COMMA
public static final byte COMMAHelper for writing comma separator: ,- See Also:
-
SEMI
public static final byte SEMIHelper for writing semicolon: :- See Also:
-
QUOTE
public static final byte QUOTEHelper for writing JSON quote: "- See Also:
-
ESCAPE
public static final byte ESCAPEHelper for writing JSON escape: \\- See Also:
-
-
Constructor Details
-
JsonWriter
JsonWriter(@Nullable UnknownSerializer unknownSerializer) -
JsonWriter
JsonWriter(int size, @Nullable UnknownSerializer unknownSerializer) -
JsonWriter
JsonWriter(byte[] buffer, @Nullable UnknownSerializer unknownSerializer)
-
-
Method Details
-
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
Write a quoted string into the JSON. String will be appropriately escaped according to JSON escaping rules.- Parameters:
value- string to write
-
writeString
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
-
writeAscii
Write string consisting of only ascii characters. String will not be escaped according to JSON escaping rules.- Parameters:
value- ascii string
-
writeAscii
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
-
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
When 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:
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
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.This is deprecated method which exists only for backward compatibility- Throws:
IOException- unable to write to target stream
-
serialize
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
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
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
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
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
-
serialize
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
-
serialize
public <K,V> void serialize(@Nullable Map<K, V> map, JsonWriter.WriteObject<K> keyEncoder, JsonWriter.WriteObject<V> valueEncoder) -
serializeRaw
public void serializeRaw(@Nullable Map map, JsonWriter.WriteObject keyEncoder, JsonWriter.WriteObject valueEncoder) -
writeQuoted
-
serializeObject
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
-