Class JsonWriter

java.lang.Object
com.dslplatform.json.JsonWriter

public final class JsonWriter extends Object
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.

  • Field Details

    • position

      private int position
    • flushed

      private long flushed
    • target

      private 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:
    • OBJECT_END

      public static final byte OBJECT_END
      Helper for writing JSON object end: }
      See Also:
    • ARRAY_START

      public static final byte ARRAY_START
      Helper for writing JSON array start: [
      See Also:
    • ARRAY_END

      public static final byte ARRAY_END
      Helper for writing JSON array end: ]
      See Also:
    • COMMA

      public static final byte COMMA
      Helper for writing comma separator: ,
      See Also:
    • SEMI

      public static final byte SEMI
      Helper for writing semicolon: :
      See Also:
    • QUOTE

      public static final byte QUOTE
      Helper for writing JSON quote: "
      See Also:
    • ESCAPE

      public static final byte ESCAPE
      Helper for writing JSON escape: \\
      See Also:
  • Constructor Details

  • 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

      public final void writeString(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(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(CharSequence str, int i, int cur, int len)
    • writeAscii

      public final void writeAscii(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(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 string
      len - 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 copy
      len - 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 copy
      offset - in buffer to start from
      len - 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 String toString()
      Overrides:
      toString in class 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(OutputStream stream) throws IOException
      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

      public final void reset(@Nullable 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 used

      To reset the stream to null use reset() or reset(OutputStream) methods.

    • close

      @Deprecated public void close() throws IOException
      Deprecated.
      This is deprecated method which exists only for backward compatibility
      Throws:
      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 objects
      len - size of array which should be serialized
    • serialize

      public <T extends JsonObject> void serialize(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 serialize
      encoder - instance serializer
    • serialize

      public <T> void serialize(@Nullable 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 serialize
      encoder - instance serializer
    • serializeRaw

      public void serializeRaw(@Nullable List list, JsonWriter.WriteObject encoder)
    • serialize

      public <T> void serialize(@Nullable 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 serialize
      encoder - instance serializer
    • serializeRaw

      public void serializeRaw(@Nullable Collection collection, JsonWriter.WriteObject encoder)
    • 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

      public <T> void writeQuoted(JsonWriter.WriteObject<T> keyWriter, T key)
    • serializeObject

      public void serializeObject(@Nullable 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