Class JsonWriter


  • public final class JsonWriter
    extends java.lang.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.

    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static interface  JsonWriter.WriteObject<T>
      Custom objects can be serialized based on the implementation specified through this interface.
    • Method Summary

      All Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      (package private) void advance​(int size)  
      void close()
      Deprecated.
      private void enlargeOrFlush​(int size, int padding)  
      (package private) byte[] ensureCapacity​(int free)  
      void flush()
      If stream was used, copies the buffer to stream and resets the position in buffer to 0.
      long flushed()
      Total bytes currently flushed to stream
      byte[] getByteBuffer()
      Current buffer.
      void reset()
      Resets the writer - same as calling reset(OutputStream = null)
      void reset​(java.io.OutputStream stream)
      Resets the writer - specifies the target stream and sets the position in buffer to 0.
      <T> void serialize​(java.util.Collection<T> collection, JsonWriter.WriteObject<T> encoder)
      Convenience method for serializing collection through instance serializer (WriteObject).
      <T extends JsonObject>
      void
      serialize​(java.util.List<T> list)
      Convenience method for serializing list of JsonObject's.
      <T> void serialize​(java.util.List<T> list, JsonWriter.WriteObject<T> encoder)
      Convenience method for serializing list through instance serializer (WriteObject).
      <K,​V>
      void
      serialize​(java.util.Map<K,​V> map, JsonWriter.WriteObject<K> keyEncoder, JsonWriter.WriteObject<V> valueEncoder)  
      <T extends JsonObject>
      void
      serialize​(T[] array)
      Convenience method for serializing array of JsonObject's.
      <T extends JsonObject>
      void
      serialize​(T[] array, int len)
      Convenience method for serializing only part of JsonObject's array.
      <T> void serialize​(T[] array, JsonWriter.WriteObject<T> encoder)
      Convenience method for serializing array through instance serializer (WriteObject).
      void serializeObject​(java.lang.Object value)
      Generic object serializer which is used for "unknown schema" objects.
      void serializeRaw​(java.util.Collection collection, JsonWriter.WriteObject encoder)  
      void serializeRaw​(java.util.List list, JsonWriter.WriteObject encoder)  
      void serializeRaw​(java.util.Map map, JsonWriter.WriteObject keyEncoder, JsonWriter.WriteObject valueEncoder)  
      int size()
      Current position in the buffer.
      byte[] toByteArray()
      Content of buffer can be copied to another array of appropriate size.
      void toStream​(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.String toString()  
      void writeAscii​(byte[] buf)
      Copy bytes into JSON as is.
      void writeAscii​(byte[] buf, int len)
      Copy part of byte buffer into JSON as is.
      void writeAscii​(java.lang.String value)
      Write string consisting of only ascii characters.
      void writeAscii​(java.lang.String value, int len)
      Write part of string consisting of only ascii characters.
      void writeBinary​(byte[] value)
      Encode bytes as Base 64.
      void writeByte​(byte value)
      Write a single byte into the JSON.
      (package private) void writeDouble​(double value)  
      void writeNull()
      Optimized method for writing 'null' into the JSON.
      <T> void writeQuoted​(JsonWriter.WriteObject<T> keyWriter, T key)  
      private void writeQuotedString​(java.lang.CharSequence str, int i, int cur, int len)  
      void writeRaw​(byte[] buf, int offset, int len)
      Copy part of byte buffer into JSON as is.
      void writeString​(java.lang.CharSequence value)
      Write a quoted string into the JSON.
      void writeString​(java.lang.String value)
      Write a quoted string into the JSON.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Field Detail

      • position

        private int position
      • flushed

        private long flushed
      • target

        private java.io.OutputStream target
      • buffer

        private byte[] buffer
      • 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
      • ESCAPE

        public static final byte ESCAPE
        Helper for writing JSON escape: \\
        See Also:
        Constant Field Values
    • 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 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 java.lang.String toString()
        Overrides:
        toString in class java.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.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:
        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 used

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

      • close

        @Deprecated
        public void close()
                   throws java.io.IOException
        Deprecated.
        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 objects
        len - 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 serialize
        encoder - 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 serialize
        encoder - instance serializer
      • 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 serialize
        encoder - instance serializer
      • 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