Class DslJson<TContext>

  • Type Parameters:
    TContext - used for library specialization. If unsure, use Object
    All Implemented Interfaces:
    TypeLookup, UnknownSerializer

    public class DslJson<TContext>
    extends java.lang.Object
    implements UnknownSerializer, TypeLookup
    Main DSL-JSON class. Easiest way to use the library is to create an DslJson<Object> instance and reuse it within application. DslJson has optional constructor for specifying default readers/writers.

    During initialization DslJson will use ServiceLoader API to load registered services. This is done through `META-INF/services/com.dslplatform.json.CompiledJson` file.

    DslJson can fallback to another serializer in case when it doesn't know how to handle specific type. This can be specified by Fallback interface during initialization.

    If you wish to use compile time databinding @CompiledJson annotation must be specified on the target class or implicit reference to target class must exists from a class with @CompiledJson annotation.

    Usage example:

         DslJson<Object> dsl = new DslJson<>();
         dsl.serialize(instance, OutputStream);
         POJO pojo = dsl.deserialize(POJO.class, InputStream);
     

    For best performance use serialization API with JsonWriter and byte[] as target. JsonWriter is reused via thread local variable. When custom JsonWriter's are used, reusing them will yield maximum performance. JsonWriter can be reused via reset methods. For best deserialization performance prefer byte[] API instead of InputStream API. JsonReader is reused via thread local variable. When custom JsonReaders are used, reusing them will yield maximum performance. JsonReader can be reused via process methods.

    During deserialization TContext can be used to pass data into deserialized classes. This is useful when deserializing domain objects which require state or service provider. For example DSL Platform entities require service locator to be able to perform lazy load.

    DslJson doesn't have a String or Reader API since it's optimized for processing bytes and streams. If you wish to process String, use String.getBytes("UTF-8") as argument for DslJson. Only UTF-8 is supported for encoding and decoding JSON.

         DslJson<Object> dsl = new DslJson<>();
         JsonWriter writer = dsl.newWriter();
         dsl.serialize(writer, instance);
         String json = writer.toString(); //JSON as string - avoid using JSON as Strings whenever possible
         byte[] input = json.getBytes("UTF-8");
         POJO pojo = dsl.deserialize(POJO.class, input, input.length);
     
    • Field Detail

      • unknownValue

        private static final java.lang.Object unknownValue
      • context

        @Nullable
        public final TContext context
        The context of this instance. Can be used for library specialization
      • omitDefaults

        public final boolean omitDefaults
        Should properties with default values be omitted from the resulting JSON? This will leave out nulls, empty collections, zeros and other attributes with default values which can be reconstructed from schema information
      • allowArrayFormat

        public final boolean allowArrayFormat
        When object supports array format, eg. [prop1, prop2, prop3] this value must be enabled before object will be serialized in such a way. Regardless of this value deserialization will support all formats.
      • settingsWriters

        private final int settingsWriters
      • settingsReaders

        private final int settingsReaders
      • settingsBinders

        private final int settingsBinders
      • maxNumberDigits

        private final int maxNumberDigits
      • maxStringSize

        private final int maxStringSize
      • localWriter

        protected final java.lang.ThreadLocal<JsonWriter> localWriter
      • localReader

        protected final java.lang.ThreadLocal<JsonReader> localReader
      • creatorMarkers

        private final java.util.Map<java.lang.Class<? extends java.lang.annotation.Annotation>,​java.lang.Boolean> creatorMarkers
      • defaults

        private final java.util.Map<java.lang.reflect.Type,​java.lang.Object> defaults
      • readers

        private final java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,​JsonReader.ReadObject> readers
      • binders

        private final java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,​JsonReader.BindObject> binders
      • writers

        private final java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,​JsonWriter.WriteObject> writers
      • writerMap

        private final java.util.concurrent.ConcurrentMap<java.lang.Class<?>,​java.lang.Class<?>> writerMap
      • EMPTY_ITERATOR

        private static final java.util.Iterator EMPTY_ITERATOR
      • NULL

        private static final byte[] NULL
    • Constructor Detail

      • DslJson

        public DslJson()
        Simple initialization entry point. Will provide null for TContext Java graphics readers/writers will not be registered. Fallback will not be configured. Key cache will be enables, values cache will be disabled. Default ServiceLoader.load method will be used to setup services from META-INF
      • DslJson

        @Deprecated
        public DslJson​(@Nullable
                       TContext context,
                       boolean javaSpecifics,
                       @Nullable
                       DslJson.Fallback<TContext> fallback,
                       boolean omitDefaults,
                       @Nullable
                       StringCache keyCache,
                       java.lang.Iterable<Configuration> serializers)
        Deprecated.
        Will be removed. Use DslJson(Settings) instead. Fully configurable entry point.
        Parameters:
        context - context instance which can be provided to deserialized objects. Use null if not sure
        javaSpecifics - register Java graphics specific classes such as java.awt.Point, Image, ...
        fallback - in case of unsupported type, try serialization/deserialization through external API
        omitDefaults - should serialization produce minified JSON (omit nulls and default values)
        keyCache - parsed keys can be cached (this is only used in small subset of parsing)
        serializers - additional serializers/deserializers which will be immediately registered into readers/writers
      • DslJson

        public DslJson​(DslJson.Settings<TContext> settings)
        Fully configurable entry point. Provide settings for DSL-JSON initialization.
        Parameters:
        settings - DSL-JSON configuration
    • Method Detail

      • newWriter

        public JsonWriter newWriter()
        Create a writer bound to this DSL-JSON. Ideally it should be reused. Bound writer can use lookups to find custom writers. This can be used to serialize unknown types such as Object.class
        Returns:
        bound writer
      • newWriter

        public JsonWriter newWriter​(int size)
        Create a writer bound to this DSL-JSON. Ideally it should be reused. Bound writer can use lookups to find custom writers. This can be used to serialize unknown types such as Object.class
        Parameters:
        size - initial buffer size
        Returns:
        bound writer
      • newWriter

        public JsonWriter newWriter​(byte[] buffer)
        Create a writer bound to this DSL-JSON. Ideally it should be reused. Bound writer can use lookups to find custom writers. This can be used to serialize unknown types such as Object.class
        Parameters:
        buffer - initial buffer
        Returns:
        bound writer
      • newReader

        public JsonReader<TContext> newReader()
        Create a reader bound to this DSL-JSON. Bound reader can reuse key cache (which is used during Map deserialization) This reader can be reused via process method.
        Returns:
        bound reader
      • newReader

        public JsonReader<TContext> newReader​(byte[] bytes)
        Create a reader bound to this DSL-JSON. Bound reader can reuse key cache (which is used during Map deserialization) This reader can be reused via process method.
        Parameters:
        bytes - input bytes
        Returns:
        bound reader
      • newReader

        public JsonReader<TContext> newReader​(byte[] bytes,
                                              int length)
        Create a reader bound to this DSL-JSON. Bound reader can reuse key cache (which is used during Map deserialization) This reader can be reused via process method.
        Parameters:
        bytes - input bytes
        length - use input bytes up to specified length
        Returns:
        bound reader
      • newReader

        public JsonReader<TContext> newReader​(byte[] bytes,
                                              int length,
                                              char[] tmp)
        Create a reader bound to this DSL-JSON. Bound reader can reuse key cache (which is used during Map deserialization) Pass in initial string buffer. This reader can be reused via process method.
        Parameters:
        bytes - input bytes
        length - use input bytes up to specified length
        tmp - string parsing buffer
        Returns:
        bound reader
      • newReader

        public JsonReader<TContext> newReader​(java.io.InputStream stream,
                                              byte[] buffer)
                                       throws java.io.IOException
        Create a reader bound to this DSL-JSON. Bound reader can reuse key cache (which is used during Map deserialization) Created reader can be reused (using process method). This is convenience method for creating a new reader and binding it to stream.
        Parameters:
        stream - input stream
        buffer - temporary buffer
        Returns:
        bound reader
        Throws:
        java.io.IOException - unable to read from stream
      • newReader

        @Deprecated
        public JsonReader<TContext> newReader​(java.lang.String input)
        Deprecated.
        Create a reader bound to this DSL-JSON. Bound reader can reuse key cache (which is used during Map deserialization) This method id Deprecated since it should be avoided. It's better to use byte[] or InputStream based readers
        Parameters:
        input - JSON string
        Returns:
        bound reader
      • loadDefaultConverters

        private static void loadDefaultConverters​(DslJson json,
                                                  java.util.Set<java.lang.ClassLoader> loaders,
                                                  java.lang.String name)
      • registerJavaSpecifics

        static void registerJavaSpecifics​(DslJson json)
      • registerDefault

        public <T> void registerDefault​(java.lang.Class<T> manifest,
                                        T instance)
      • getDefault

        @Nullable
        public final java.lang.Object getDefault​(@Nullable
                                                 java.lang.reflect.Type manifest)
      • getRegisteredDecoders

        public final java.util.Set<java.lang.reflect.Type> getRegisteredDecoders()
      • getRegisteredBinders

        public final java.util.Set<java.lang.reflect.Type> getRegisteredBinders()
      • getRegisteredEncoders

        public final java.util.Set<java.lang.reflect.Type> getRegisteredEncoders()
      • getRegisteredCreatorMarkers

        public final java.util.Map<java.lang.Class<? extends java.lang.annotation.Annotation>,​java.lang.Boolean> getRegisteredCreatorMarkers()
      • registerReader

        public <T,​S extends T> void registerReader​(java.lang.Class<T> manifest,
                                                         @Nullable
                                                         JsonReader.ReadObject<S> reader)
        Register custom reader for specific type (JSON -> instance conversion). Reader is used for conversion from input byte[] -> target object instance

        Types registered through @CompiledJson annotation should be registered automatically through ServiceLoader.load method and you should not be registering them manually.

        If null is registered for a reader this will disable deserialization of specified type

        Type Parameters:
        T - type
        S - type or subtype
        Parameters:
        manifest - specified type
        reader - provide custom implementation for reading JSON into an object instance
      • registerReader

        @Nullable
        public JsonReader.ReadObject registerReader​(java.lang.reflect.Type manifest,
                                                    @Nullable
                                                    JsonReader.ReadObject<?> reader)
        Register custom reader for specific type (JSON -> instance conversion). Reader is used for conversion from input byte[] -> target object instance

        Types registered through @CompiledJson annotation should be registered automatically through ServiceLoader.load method and you should not be registering them manually.

        If null is registered for a reader this will disable deserialization of specified type

        Parameters:
        manifest - specified type
        reader - provide custom implementation for reading JSON into an object instance
        Returns:
        old registered value
      • registerBinder

        public <T,​S extends T> void registerBinder​(java.lang.Class<T> manifest,
                                                         @Nullable
                                                         JsonReader.BindObject<S> binder)
        Register custom binder for specific type (JSON -> instance conversion). Binder is used for conversion from input byte[] -> existing target object instance. It's similar to reader, with the difference that it accepts target instance.

        Types registered through @CompiledJson annotation should be registered automatically through ServiceLoader.load method and you should not be registering them manually.

        If null is registered for a binder this will disable binding of specified type

        Type Parameters:
        T - type
        S - type or subtype
        Parameters:
        manifest - specified type
        binder - provide custom implementation for binding JSON to an object instance
      • registerBinder

        public void registerBinder​(java.lang.reflect.Type manifest,
                                   @Nullable
                                   JsonReader.BindObject<?> binder)
        Register custom binder for specific type (JSON -> instance conversion). Binder is used for conversion from input byte[] -> existing target object instance. It's similar to reader, with the difference that it accepts target instance.

        Types registered through @CompiledJson annotation should be registered automatically through ServiceLoader.load method and you should not be registering them manually.

        If null is registered for a binder this will disable binding of specified type

        Parameters:
        manifest - specified type
        binder - provide custom implementation for binding JSON to an object instance
      • registerWriter

        public <T> void registerWriter​(java.lang.Class<T> manifest,
                                       @Nullable
                                       JsonWriter.WriteObject<T> writer)
        Register custom writer for specific type (instance -> JSON conversion). Writer is used for conversion from object instance -> output byte[]

        Types registered through @CompiledJson annotation should be registered automatically through ServiceLoader.load method and you should not be registering them manually.

        If null is registered for a writer this will disable serialization of specified type

        Type Parameters:
        T - type
        Parameters:
        manifest - specified type
        writer - provide custom implementation for writing JSON from object instance
      • registerWriter

        @Nullable
        public JsonWriter.WriteObject registerWriter​(java.lang.reflect.Type manifest,
                                                     @Nullable
                                                     JsonWriter.WriteObject<?> writer)
        Register custom writer for specific type (instance -> JSON conversion). Writer is used for conversion from object instance -> output byte[]

        Types registered through @CompiledJson annotation should be registered automatically through ServiceLoader.load method and you should not be registering them manually.

        If null is registered for a writer this will disable serialization of specified type

        Parameters:
        manifest - specified type
        writer - provide custom implementation for writing JSON from object instance
        Returns:
        old registered value
      • tryFindWriter

        @Nullable
        public JsonWriter.WriteObject<?> tryFindWriter​(java.lang.reflect.Type manifest)
        Try to find registered writer for provided type. If writer is not found, null will be returned. If writer for exact type is not found, type hierarchy will be scanned for base writer.

        Writer is used for conversion from object instance into JSON representation.

        Parameters:
        manifest - specified type
        Returns:
        writer for specified type if found
      • extractActualType

        private static java.lang.reflect.Type extractActualType​(java.lang.reflect.Type manifest)
      • checkExternal

        private <T> void checkExternal​(java.lang.reflect.Type manifest,
                                       java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,​T> cache)
      • lookupFromFactories

        @Nullable
        private <T> T lookupFromFactories​(java.lang.reflect.Type signature,
                                          java.lang.reflect.Type manifest,
                                          java.util.List<DslJson.ConverterFactory<T>> factories,
                                          java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,​T> cache)
      • tryFindReader

        @Nullable
        public JsonReader.ReadObject<?> tryFindReader​(java.lang.reflect.Type manifest)
        Try to find registered reader for provided type. If reader is not found, null will be returned. Exact match must be found, type hierarchy will not be scanned for alternative readers.

        If you wish to use alternative reader for specific type, register it manually with something along the lines of

             DslJson dslJson = ...
             dslJson.registerReader(Interface.class, dslJson.tryFindReader(Implementation.class));
         
        Parameters:
        manifest - specified type
        Returns:
        found reader for specified type
      • tryFindBinder

        @Nullable
        public JsonReader.BindObject<?> tryFindBinder​(java.lang.reflect.Type manifest)
        Try to find registered binder for provided type. If binder is not found, null will be returned. Exact match must be found, type hierarchy will not be scanned for alternative binders.

        If you wish to use alternative binder for specific type, register it manually with something along the lines of

             DslJson dslJson = ...
             dslJson.registerBinder(Interface.class, dslJson.tryFindBinder(Implementation.class));
         
        Parameters:
        manifest - specified type
        Returns:
        found reader for specified type
      • tryFindWriter

        @Nullable
        public <T> JsonWriter.WriteObject<T> tryFindWriter​(java.lang.Class<T> manifest)
        Try to find registered writer for provided type. If writer is not found, null will be returned. If writer for exact type is not found, type hierarchy will be scanned for base writer.

        Writer is used for conversion from object instance into JSON representation.

        Type Parameters:
        T - specified type
        Parameters:
        manifest - specified class
        Returns:
        found writer for specified class or null
      • tryFindReader

        @Nullable
        public <T> JsonReader.ReadObject<T> tryFindReader​(java.lang.Class<T> manifest)
        Try to find registered reader for provided type. If reader is not found, null will be returned. Exact match must be found, type hierarchy will not be scanned for alternative reader.

        If you wish to use alternative reader for specific type, register it manually with something along the lines of

             DslJson dslJson = ...
             dslJson.registerReader(Interface.class, dslJson.tryFindReader(Implementation.class));
         
        Specified by:
        tryFindReader in interface TypeLookup
        Type Parameters:
        T - specified type
        Parameters:
        manifest - specified class
        Returns:
        found reader for specified class or null
      • tryFindBinder

        @Nullable
        public <T> JsonReader.BindObject<T> tryFindBinder​(java.lang.Class<T> manifest)
        Try to find registered binder for provided type. If binder is not found, null will be returned. Exact match must be found, type hierarchy will not be scanned for alternative binder.

        If you wish to use alternative binder for specific type, register it manually with something along the lines of

             DslJson dslJson = ...
             dslJson.registerBinder(Interface.class, dslJson.tryFindBinder(Implementation.class));
         
        Specified by:
        tryFindBinder in interface TypeLookup
        Type Parameters:
        T - specified type
        Parameters:
        manifest - specified class
        Returns:
        found reader for specified class or null
      • findAllSignatures

        private static void findAllSignatures​(java.lang.Class<?> manifest,
                                              java.util.ArrayList<java.lang.Class<?>> found)
      • serializeMap

        public void serializeMap​(java.util.Map<java.lang.String,​java.lang.Object> value,
                                 JsonWriter sw)
                          throws java.io.IOException
        Throws:
        java.io.IOException
      • deserializeObject

        @Deprecated
        @Nullable
        public static java.lang.Object deserializeObject​(JsonReader reader)
                                                  throws java.io.IOException
        Deprecated.
        Throws:
        java.io.IOException
      • deserializeList

        @Deprecated
        public static java.util.ArrayList<java.lang.Object> deserializeList​(JsonReader reader)
                                                                     throws java.io.IOException
        Deprecated.
        Will be removed
        Parameters:
        reader - JSON reader
        Returns:
        deseralized list
        Throws:
        java.io.IOException - error during parsing
      • deserializeMap

        @Deprecated
        public static java.util.LinkedHashMap<java.lang.String,​java.lang.Object> deserializeMap​(JsonReader reader)
                                                                                               throws java.io.IOException
        Deprecated.
        Will be removed
        Parameters:
        reader - JSON reader
        Returns:
        deserialized map
        Throws:
        java.io.IOException - error during parsing
      • convertResultToArray

        private static java.lang.Object convertResultToArray​(java.lang.Class<?> elementType,
                                                             java.util.List<?> result)
      • canSerialize

        public final boolean canSerialize​(java.lang.reflect.Type manifest)
        Check if DslJson knows how to serialize a type. It will check if a writer for such type exists or can be used.
        Parameters:
        manifest - type to check
        Returns:
        can serialize this type into JSON
      • canDeserialize

        public final boolean canDeserialize​(java.lang.reflect.Type manifest)
        Check if DslJson knows how to deserialize a type. It will check if a reader for such type exists or can be used.
        Parameters:
        manifest - type to check
        Returns:
        can read this type from JSON
      • deserialize

        @Nullable
        public <T> T deserialize​(JsonReader.ReadObject<T> converter,
                                 JsonReader<TContext> input)
                          throws java.io.IOException
        Reusable deserialize API. For maximum performance `JsonReader` should be reused (otherwise small buffer will be allocated for processing) and `JsonReader.ReadObject` should be prepared (otherwise a lookup will be required).

        This is mostly convenience API since it starts the processing of the JSON by calling getNextToken on JsonReader, checks for null and calls converter.read(input).

        Type Parameters:
        T - specified type
        Parameters:
        converter - target reader
        input - input JSON
        Returns:
        deserialized instance
        Throws:
        java.io.IOException - error during deserialization
      • deserialize

        @Nullable
        public <TResult> TResult deserialize​(java.lang.Class<TResult> manifest,
                                             byte[] body,
                                             int size)
                                      throws java.io.IOException
        Convenient deserialize API for working with bytes. Deserialize provided byte input into target object.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        Type Parameters:
        TResult - target type
        Parameters:
        manifest - target type
        body - input JSON
        size - length
        Returns:
        deserialized instance
        Throws:
        java.io.IOException - error during deserialization
      • deserialize

        @Nullable
        public java.lang.Object deserialize​(java.lang.reflect.Type manifest,
                                            byte[] body,
                                            int size)
                                     throws java.io.IOException
        Deserialize API for working with bytes. Deserialize provided byte input into target object.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        Parameters:
        manifest - target type
        body - input JSON
        size - length
        Returns:
        deserialized instance
        Throws:
        java.io.IOException - error during deserialization
      • deserializeWith

        @Nullable
        protected java.lang.Object deserializeWith​(java.lang.reflect.Type manifest,
                                                   JsonReader json)
                                            throws java.io.IOException
        Throws:
        java.io.IOException
      • returnAsArray

        private static java.lang.Object returnAsArray​(java.lang.reflect.Type content,
                                                      java.util.ArrayList<?> result)
      • returnEmptyArray

        private static java.lang.Object returnEmptyArray​(java.lang.reflect.Type content)
      • createErrorMessage

        protected java.io.IOException createErrorMessage​(java.lang.Class<?> manifest)
      • deserializeList

        @Nullable
        public <TResult> java.util.List<TResult> deserializeList​(java.lang.Class<TResult> manifest,
                                                                 byte[] body,
                                                                 int size)
                                                          throws java.io.IOException
        Convenient deserialize list API for working with bytes. Deserialize provided byte input into target object.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        Type Parameters:
        TResult - target element type
        Parameters:
        manifest - target type
        body - input JSON
        size - length
        Returns:
        deserialized list instance
        Throws:
        java.io.IOException - error during deserialization
      • deserializeList

        @Nullable
        public <TResult> java.util.List<TResult> deserializeList​(java.lang.Class<TResult> manifest,
                                                                 java.io.InputStream stream,
                                                                 byte[] buffer)
                                                          throws java.io.IOException
        This is deprecated to avoid using it. Use deserializeList method without the buffer argument instead. Convenient deserialize list API for working with streams. Deserialize provided stream input into target object. Use buffer for internal conversion from stream into byte[] for partial processing. This method creates a new instance of JsonReader. There is also deserializeList without the buffer which reuses thread local reader.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        When working on InputStream DslJson will process JSON in chunks of byte[] inputs. Provided buffer will be used as input for partial processing.

        For best performance buffer should be reused.

        Type Parameters:
        TResult - target element type
        Parameters:
        manifest - target type
        stream - input JSON
        buffer - buffer used for InputStream -> byte[] conversion
        Returns:
        deserialized list
        Throws:
        java.io.IOException - error during deserialization
      • deserializeList

        @Nullable
        public <TResult> java.util.List<TResult> deserializeList​(java.lang.Class<TResult> manifest,
                                                                 java.io.InputStream stream)
                                                          throws java.io.IOException
        Convenient deserialize list API for working with streams. Deserialize provided stream input into target object.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        When working on InputStream DslJson will process JSON in chunks of byte[] inputs.

        Type Parameters:
        TResult - target element type
        Parameters:
        manifest - target type
        stream - input JSON
        Returns:
        deserialized list
        Throws:
        java.io.IOException - error during deserialization
      • deserializeList

        @Nullable
        protected <TResult> java.util.List<TResult> deserializeList​(java.lang.Class<TResult> manifest,
                                                                    JsonReader<TContext> json,
                                                                    java.io.InputStream stream)
                                                             throws java.io.IOException
        Throws:
        java.io.IOException
      • deserialize

        @Nullable
        public <TResult> TResult deserialize​(java.lang.Class<TResult> manifest,
                                             java.io.InputStream stream,
                                             byte[] buffer)
                                      throws java.io.IOException
        Convenient deserialize API for working with streams. Deserialize provided stream input into target object. This method accepts a buffer and will create a new reader using provided buffer. This buffer is used for internal conversion from stream into byte[] for partial processing. There is also method without the buffer which reuses local thread reader for processing.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        When working on InputStream DslJson will process JSON in chunks of byte[] inputs. Provided buffer will be used as input for partial processing.

        For best performance buffer should be reused.

        Type Parameters:
        TResult - target type
        Parameters:
        manifest - target type
        stream - input JSON
        buffer - buffer used for InputStream -> byte[] conversion
        Returns:
        deserialized instance
        Throws:
        java.io.IOException - error during deserialization
      • deserialize

        @Nullable
        public <TResult> TResult deserialize​(java.lang.Class<TResult> manifest,
                                             java.io.InputStream stream)
                                      throws java.io.IOException
        Convenient deserialize API for working with streams. Deserialize provided stream input into target object. This method reuses thread local reader for processing input stream.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        When working on InputStream DslJson will process JSON in chunks of byte[] inputs.

        Type Parameters:
        TResult - target type
        Parameters:
        manifest - target type
        stream - input JSON
        Returns:
        deserialized instance
        Throws:
        java.io.IOException - error during deserialization
      • deserialize

        @Nullable
        protected <TResult> TResult deserialize​(java.lang.Class<TResult> manifest,
                                                JsonReader json,
                                                java.io.InputStream stream)
                                         throws java.io.IOException
        Throws:
        java.io.IOException
      • deserialize

        @Nullable
        public java.lang.Object deserialize​(java.lang.reflect.Type manifest,
                                            java.io.InputStream stream,
                                            byte[] buffer)
                                     throws java.io.IOException
        Deserialize API for working with streams. Deserialize provided stream input into target object. Use buffer for internal conversion from stream into byte[] for partial processing. This method creates a new instance of JsonReader for processing the stream. There is also a method without the byte[] buffer which reuses thread local reader.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them. DslJson will treat input as a sequence of bytes which allows for various optimizations.

        When working on InputStream DslJson will process JSON in chunks of byte[] inputs. Provided buffer will be used as input for partial processing.

        For best performance buffer should be reused.

        Parameters:
        manifest - target type
        stream - input JSON
        buffer - buffer used for InputStream -> byte[] conversion
        Returns:
        deserialized instance
        Throws:
        java.io.IOException - error during deserialization
      • deserialize

        @Nullable
        public java.lang.Object deserialize​(java.lang.reflect.Type manifest,
                                            java.io.InputStream stream)
                                     throws java.io.IOException
        Deserialize API for working with streams. Deserialize provided stream input into target object. This method reuses thread local reader for processing JSON input.

        Since JSON is often though of as a series of char, most libraries will convert inputs into a sequence of chars and do processing on them.

        When working on InputStream DslJson will process JSON in chunks of byte[] inputs.

        Parameters:
        manifest - target type
        stream - input JSON
        Returns:
        deserialized instance
        Throws:
        java.io.IOException - error during deserialization
      • iterateOver

        @Nullable
        public <TResult> java.util.Iterator<TResult> iterateOver​(java.lang.Class<TResult> manifest,
                                                                 java.io.InputStream stream)
                                                          throws java.io.IOException
        Streaming API for collection deserialization. DslJson will create iterator based on provided manifest info. It will attempt to deserialize from stream on each next() invocation. This method requires buffer instance for partial stream processing. It will create a new instance of JsonReader. There is also a method without the buffer which will reuse thread local reader.

        Useful for processing very large streams if only one instance from collection is required at once.

        Stream will be processed in chunks of specified buffer byte[]. It will block on reading until buffer is full or end of stream is detected.

        Type Parameters:
        TResult - type info
        Parameters:
        manifest - type info
        stream - JSON data stream
        Returns:
        Iterator to instances deserialized from input JSON
        Throws:
        java.io.IOException - if reader is not found or there is an error processing input stream
      • iterateOver

        @Nullable
        public <TResult> java.util.Iterator<TResult> iterateOver​(java.lang.Class<TResult> manifest,
                                                                 java.io.InputStream stream,
                                                                 byte[] buffer)
                                                          throws java.io.IOException
        Streaming API for collection deserialization. DslJson will create iterator based on provided manifest info. It will attempt to deserialize from stream on each next() invocation. This method requires buffer instance for partial stream processing. It will create a new instance of JsonReader. There is also a method without the buffer which will reuse thread local reader.

        Useful for processing very large streams if only one instance from collection is required at once.

        Stream will be processed in chunks of specified buffer byte[]. It will block on reading until buffer is full or end of stream is detected.

        Type Parameters:
        TResult - type info
        Parameters:
        manifest - type info
        stream - JSON data stream
        buffer - size of processing chunk
        Returns:
        Iterator to instances deserialized from input JSON
        Throws:
        java.io.IOException - if reader is not found or there is an error processing input stream
      • iterateOver

        @Nullable
        protected <TResult> java.util.Iterator<TResult> iterateOver​(java.lang.Class<TResult> manifest,
                                                                    JsonReader json,
                                                                    java.io.InputStream stream)
                                                             throws java.io.IOException
        Throws:
        java.io.IOException
      • getOrCreateWriter

        private JsonWriter.WriteObject getOrCreateWriter​(@Nullable
                                                         java.lang.Object instance,
                                                         java.lang.Class<?> instanceManifest)
                                                  throws java.io.IOException
        Throws:
        java.io.IOException
      • iterateOver

        public <T> void iterateOver​(java.util.Iterator<T> iterator,
                                    java.io.OutputStream stream,
                                    @Nullable
                                    JsonWriter writer)
                             throws java.io.IOException
        Streaming API for collection serialization.

        It will iterate over entire iterator and serialize each instance into target output stream. After each instance serialization it will copy JSON into target output stream. During each serialization reader will be looked up based on next() instance which allows serializing collection with different types. If collection contains all instances of the same type, prefer the other streaming API.

        If reader is not found an IOException will be thrown

        If JsonWriter is provided it will be used, otherwise a new instance will be internally created.

        Type Parameters:
        T - input data type
        Parameters:
        iterator - input data
        stream - target JSON stream
        writer - temporary buffer for serializing a single item. Can be null
        Throws:
        java.io.IOException - reader is not found, there is an error during serialization or problem with writing to target stream
      • iterateOver

        public <T> void iterateOver​(java.util.Iterator<T> iterator,
                                    java.lang.Class<T> manifest,
                                    java.io.OutputStream stream,
                                    @Nullable
                                    JsonWriter writer)
                             throws java.io.IOException
        Streaming API for collection serialization.

        It will iterate over entire iterator and serialize each instance into target output stream. After each instance serialization it will copy JSON into target output stream.

        If reader is not found an IOException will be thrown

        If JsonWriter is provided it will be used, otherwise a new instance will be internally created.

        Type Parameters:
        T - input data type
        Parameters:
        iterator - input data
        manifest - type of elements in collection
        stream - target JSON stream
        writer - temporary buffer for serializing a single item. Can be null
        Throws:
        java.io.IOException - reader is not found, there is an error during serialization or problem with writing to target stream
      • serialize

        @Deprecated
        public <T extends JsonObject> void serialize​(JsonWriter writer,
                                                     @Nullable
                                                     T[] array)
        Deprecated.
        Use writer.serialize instead
        Type Parameters:
        T - type
        Parameters:
        writer - writer
        array - items
      • serialize

        @Deprecated
        public <T extends JsonObject> void serialize​(JsonWriter writer,
                                                     T[] array,
                                                     int len)
        Deprecated.
        Use writer.serialize instead
        Type Parameters:
        T - type
        Parameters:
        writer - writer
        array - items
        len - part of array
      • serialize

        @Deprecated
        public <T extends JsonObject> void serialize​(JsonWriter writer,
                                                     @Nullable
                                                     java.util.List<T> list)
        Deprecated.
        Use writer.serialize instead
        Type Parameters:
        T - type
        Parameters:
        writer - writer
        list - items
      • serialize

        @Deprecated
        public <T extends JsonObject> void serialize​(JsonWriter writer,
                                                     @Nullable
                                                     java.util.Collection<T> collection)
        Deprecated.
        Use writer.serialize instead
        Type Parameters:
        T - type
        Parameters:
        writer - writer
        collection - items
      • serialize

        public boolean serialize​(JsonWriter writer,
                                 java.lang.reflect.Type manifest,
                                 @Nullable
                                 java.lang.Object value)
        Generic serialize API. Based on provided type manifest converter will be chosen. If converter is not found method will return false.

        Resulting JSON will be written into provided writer argument. In case of successful serialization true will be returned.

        For best performance writer argument should be reused.

        Parameters:
        writer - where to write resulting JSON
        manifest - type manifest
        value - instance to serialize
        Returns:
        successful serialization
      • serialize

        public final void serialize​(@Nullable
                                    java.lang.Object value,
                                    java.io.OutputStream stream)
                             throws java.io.IOException
        Convenient serialize API. In most cases JSON is serialized into target `OutputStream`. This method will reuse thread local instance of `JsonWriter` and serialize JSON into it.
        Parameters:
        value - instance to serialize
        stream - where to write resulting JSON
        Throws:
        java.io.IOException - error when unable to serialize instance
      • serialize

        public final void serialize​(JsonWriter writer,
                                    @Nullable
                                    java.lang.Object value)
                             throws java.io.IOException
        Main serialization API. Convert object instance into JSON.

        JsonWriter contains a growable byte[] where JSON will be serialized. After serialization JsonWriter can be copied into OutputStream or it's byte[] can be obtained

        For best performance reuse `JsonWriter` or even better call `JsonWriter.WriteObject` directly

        Specified by:
        serialize in interface UnknownSerializer
        Parameters:
        writer - where to write resulting JSON
        value - object instance to serialize
        Throws:
        java.io.IOException - error when unable to serialize instance