Class DslJson<TContext>
- java.lang.Object
-
- com.dslplatform.json.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);
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceDslJson.ConverterFactory<T>static interfaceDslJson.Fallback<TContext>(package private) static classDslJson.RereadStreamstatic classDslJson.Settings<TContext>Configuration for DslJson options.static classDslJson.SimpleStringCacheSimplistic string cache implementation.
-
Field Summary
Fields Modifier and Type Field Description booleanallowArrayFormatWhen object supports array format, eg.protected java.util.List<DslJson.ConverterFactory<JsonReader.BindObject>>binderFactoriesprivate java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,JsonReader.BindObject>bindersprivate static JsonWriter.WriteObjectCHAR_ARRAY_WRITERTContextcontextThe context of this instance.private java.util.Map<java.lang.Class<? extends java.lang.annotation.Annotation>,java.lang.Boolean>creatorMarkersprivate java.util.Map<java.lang.reflect.Type,java.lang.Object>defaultsprivate JsonReader.DoublePrecisiondoublePrecisionprivate static java.util.IteratorEMPTY_ITERATORprivate JsonReader.ErrorInfoerrorInfoprivate ExternalConverterAnalyzerexternalConverterAnalyzerprotected DslJson.Fallback<TContext>fallbackprotected StringCachekeyCacheprotected java.lang.ThreadLocal<JsonReader>localReaderprotected java.lang.ThreadLocal<JsonWriter>localWriterprivate intmaxNumberDigitsprivate intmaxStringSizeprivate static byte[]NULLprivate JsonWriter.WriteObjectNULL_WRITERprivate JsonWriter.WriteObjectOBJECT_ARRAY_WRITERprivate JsonWriter.WriteObject<JsonObject>OBJECT_WRITERprivate java.util.concurrent.ConcurrentMap<java.lang.Class<?>,JsonReader.ReadJsonObject<JsonObject>>objectReadersbooleanomitDefaultsShould 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 informationprotected java.util.List<DslJson.ConverterFactory<JsonReader.ReadObject>>readerFactoriesprivate java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,JsonReader.ReadObject>readersprivate intsettingsBindersprivate intsettingsReadersprivate intsettingsWritersprivate JsonReader.UnknownNumberParsingunknownNumbersprivate static java.lang.ObjectunknownValueprotected StringCachevaluesCacheprotected java.util.List<DslJson.ConverterFactory<JsonWriter.WriteObject>>writerFactoriesprivate java.util.concurrent.ConcurrentMap<java.lang.Class<?>,java.lang.Class<?>>writerMapprivate java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,JsonWriter.WriteObject>writers
-
Constructor Summary
Constructors Constructor Description DslJson()Simple initialization entry point.DslJson(DslJson.Settings<TContext> settings)Fully configurable entry point.DslJson(TContext context, boolean javaSpecifics, DslJson.Fallback<TContext> fallback, boolean omitDefaults, StringCache keyCache, java.lang.Iterable<Configuration> serializers)Deprecated.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description booleancanDeserialize(java.lang.reflect.Type manifest)Check if DslJson knows how to deserialize a type.booleancanSerialize(java.lang.reflect.Type manifest)Check if DslJson knows how to serialize a type.private <T> voidcheckExternal(java.lang.reflect.Type manifest, java.util.concurrent.ConcurrentMap<java.lang.reflect.Type,T> cache)private static java.lang.ObjectconvertResultToArray(java.lang.Class<?> elementType, java.util.List<?> result)private <T extends JsonObject>
JsonReader.ReadObject<T>convertToReader(JsonReader.ReadJsonObject<T> decoder)protected java.io.IOExceptioncreateErrorMessage(java.lang.Class<?> manifest)<T> Tdeserialize(JsonReader.ReadObject<T> converter, JsonReader<TContext> input)Reusable deserialize API.<TResult> TResultdeserialize(java.lang.Class<TResult> manifest, byte[] body, int size)Convenient deserialize API for working with bytes.protected <TResult> TResultdeserialize(java.lang.Class<TResult> manifest, JsonReader json, java.io.InputStream stream)<TResult> TResultdeserialize(java.lang.Class<TResult> manifest, java.io.InputStream stream)Convenient deserialize API for working with streams.<TResult> TResultdeserialize(java.lang.Class<TResult> manifest, java.io.InputStream stream, byte[] buffer)Convenient deserialize API for working with streams.java.lang.Objectdeserialize(java.lang.reflect.Type manifest, byte[] body, int size)Deserialize API for working with bytes.java.lang.Objectdeserialize(java.lang.reflect.Type manifest, java.io.InputStream stream)Deserialize API for working with streams.java.lang.Objectdeserialize(java.lang.reflect.Type manifest, java.io.InputStream stream, byte[] buffer)Deserialize API for working with streams.static java.util.ArrayList<java.lang.Object>deserializeList(JsonReader reader)Deprecated.<TResult> java.util.List<TResult>deserializeList(java.lang.Class<TResult> manifest, byte[] body, int size)Convenient deserialize list API for working with bytes.protected <TResult> java.util.List<TResult>deserializeList(java.lang.Class<TResult> manifest, JsonReader<TContext> json, java.io.InputStream stream)<TResult> java.util.List<TResult>deserializeList(java.lang.Class<TResult> manifest, java.io.InputStream stream)Convenient deserialize list API for working with streams.<TResult> java.util.List<TResult>deserializeList(java.lang.Class<TResult> manifest, java.io.InputStream stream, byte[] buffer)This is deprecated to avoid using it.static java.util.LinkedHashMap<java.lang.String,java.lang.Object>deserializeMap(JsonReader reader)Deprecated.static java.lang.ObjectdeserializeObject(JsonReader reader)Deprecated.protected java.lang.ObjectdeserializeWith(java.lang.reflect.Type manifest, JsonReader json)private static java.lang.reflect.TypeextractActualType(java.lang.reflect.Type manifest)private static voidfindAllSignatures(java.lang.Class<?> manifest, java.util.ArrayList<java.lang.Class<?>> found)java.lang.ObjectgetDefault(java.lang.reflect.Type manifest)protected JsonReader.ReadJsonObject<JsonObject>getObjectReader(java.lang.Class<?> manifest)private JsonWriter.WriteObjectgetOrCreateWriter(java.lang.Object instance, java.lang.Class<?> instanceManifest)java.util.Set<java.lang.reflect.Type>getRegisteredBinders()java.util.Map<java.lang.Class<? extends java.lang.annotation.Annotation>,java.lang.Boolean>getRegisteredCreatorMarkers()java.util.Set<java.lang.reflect.Type>getRegisteredDecoders()java.util.Set<java.lang.reflect.Type>getRegisteredEncoders()protected <TResult> java.util.Iterator<TResult>iterateOver(java.lang.Class<TResult> manifest, JsonReader json, java.io.InputStream stream)<TResult> java.util.Iterator<TResult>iterateOver(java.lang.Class<TResult> manifest, java.io.InputStream stream)Streaming API for collection deserialization.<TResult> java.util.Iterator<TResult>iterateOver(java.lang.Class<TResult> manifest, java.io.InputStream stream, byte[] buffer)Streaming API for collection deserialization.<T> voiditerateOver(java.util.Iterator<T> iterator, java.io.OutputStream stream, JsonWriter writer)Streaming API for collection serialization.<T> voiditerateOver(java.util.Iterator<T> iterator, java.lang.Class<T> manifest, java.io.OutputStream stream, JsonWriter writer)Streaming API for collection serialization.private static voidloadDefaultConverters(DslJson json, java.util.Set<java.lang.ClassLoader> loaders, java.lang.String name)private <T> TlookupFromFactories(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)JsonReader<TContext>newReader()Create a reader bound to this DSL-JSON.JsonReader<TContext>newReader(byte[] bytes)Create a reader bound to this DSL-JSON.JsonReader<TContext>newReader(byte[] bytes, int length)Create a reader bound to this DSL-JSON.JsonReader<TContext>newReader(byte[] bytes, int length, char[] tmp)Create a reader bound to this DSL-JSON.JsonReader<TContext>newReader(java.io.InputStream stream, byte[] buffer)Create a reader bound to this DSL-JSON.JsonReader<TContext>newReader(java.lang.String input)Deprecated.JsonWriternewWriter()Create a writer bound to this DSL-JSON.JsonWriternewWriter(byte[] buffer)Create a writer bound to this DSL-JSON.JsonWriternewWriter(int size)Create a writer bound to this DSL-JSON.private JsonReader.ReadJsonObject<JsonObject>probeForObjectReader(java.lang.Class<?> manifest, java.lang.Object instance)<T,S extends T>
voidregisterBinder(java.lang.Class<T> manifest, JsonReader.BindObject<S> binder)Register custom binder for specific type (JSON -> instance conversion).voidregisterBinder(java.lang.reflect.Type manifest, JsonReader.BindObject<?> binder)Register custom binder for specific type (JSON -> instance conversion).booleanregisterBinderFactory(DslJson.ConverterFactory<? extends JsonReader.BindObject> factory)<T> voidregisterDefault(java.lang.Class<T> manifest, T instance)(package private) static voidregisterJavaSpecifics(DslJson json)<T,S extends T>
voidregisterReader(java.lang.Class<T> manifest, JsonReader.ReadObject<S> reader)Register custom reader for specific type (JSON -> instance conversion).JsonReader.ReadObjectregisterReader(java.lang.reflect.Type manifest, JsonReader.ReadObject<?> reader)Register custom reader for specific type (JSON -> instance conversion).booleanregisterReaderFactory(DslJson.ConverterFactory<? extends JsonReader.ReadObject> factory)<T> voidregisterWriter(java.lang.Class<T> manifest, JsonWriter.WriteObject<T> writer)Register custom writer for specific type (instance -> JSON conversion).JsonWriter.WriteObjectregisterWriter(java.lang.reflect.Type manifest, JsonWriter.WriteObject<?> writer)Register custom writer for specific type (instance -> JSON conversion).booleanregisterWriterFactory(DslJson.ConverterFactory<? extends JsonWriter.WriteObject> factory)private static java.lang.ObjectreturnAsArray(java.lang.reflect.Type content, java.util.ArrayList<?> result)private static java.lang.ObjectreturnEmptyArray(java.lang.reflect.Type content)voidserialize(JsonWriter writer, java.lang.Object value)Main serialization API.booleanserialize(JsonWriter writer, java.lang.reflect.Type manifest, java.lang.Object value)Generic serialize API.<T extends JsonObject>
voidserialize(JsonWriter writer, java.util.Collection<T> collection)Deprecated.<T extends JsonObject>
voidserialize(JsonWriter writer, java.util.List<T> list)Deprecated.<T extends JsonObject>
voidserialize(JsonWriter writer, T[] array)Deprecated.<T extends JsonObject>
voidserialize(JsonWriter writer, T[] array, int len)Deprecated.voidserialize(java.lang.Object value, java.io.OutputStream stream)Convenient serialize API.voidserializeMap(java.util.Map<java.lang.String,java.lang.Object> value, JsonWriter sw)<T> JsonReader.BindObject<T>tryFindBinder(java.lang.Class<T> manifest)Try to find registered binder for provided type.JsonReader.BindObject<?>tryFindBinder(java.lang.reflect.Type manifest)Try to find registered binder for provided type.<T> JsonReader.ReadObject<T>tryFindReader(java.lang.Class<T> manifest)Try to find registered reader for provided type.JsonReader.ReadObject<?>tryFindReader(java.lang.reflect.Type manifest)Try to find registered reader for provided type.<T> JsonWriter.WriteObject<T>tryFindWriter(java.lang.Class<T> manifest)Try to find registered writer for provided type.JsonWriter.WriteObject<?>tryFindWriter(java.lang.reflect.Type manifest)Try to find registered writer for provided type.
-
-
-
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
-
fallback
@Nullable protected final DslJson.Fallback<TContext> fallback
-
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.
-
keyCache
protected final StringCache keyCache
-
valuesCache
protected final StringCache valuesCache
-
writerFactories
protected final java.util.List<DslJson.ConverterFactory<JsonWriter.WriteObject>> writerFactories
-
settingsWriters
private final int settingsWriters
-
readerFactories
protected final java.util.List<DslJson.ConverterFactory<JsonReader.ReadObject>> readerFactories
-
settingsReaders
private final int settingsReaders
-
binderFactories
protected final java.util.List<DslJson.ConverterFactory<JsonReader.BindObject>> binderFactories
-
settingsBinders
private final int settingsBinders
-
errorInfo
private final JsonReader.ErrorInfo errorInfo
-
doublePrecision
private final JsonReader.DoublePrecision doublePrecision
-
unknownNumbers
private final JsonReader.UnknownNumberParsing unknownNumbers
-
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
-
externalConverterAnalyzer
private final ExternalConverterAnalyzer externalConverterAnalyzer
-
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
-
objectReaders
private final java.util.concurrent.ConcurrentMap<java.lang.Class<?>,JsonReader.ReadJsonObject<JsonObject>> objectReaders
-
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
-
OBJECT_WRITER
private final JsonWriter.WriteObject<JsonObject> OBJECT_WRITER
-
OBJECT_ARRAY_WRITER
private final JsonWriter.WriteObject OBJECT_ARRAY_WRITER
-
CHAR_ARRAY_WRITER
private static final JsonWriter.WriteObject CHAR_ARRAY_WRITER
-
NULL_WRITER
private final JsonWriter.WriteObject NULL_WRITER
-
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 surejavaSpecifics- register Java graphics specific classes such as java.awt.Point, Image, ...fallback- in case of unsupported type, try serialization/deserialization through external APIomitDefaults- 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 byteslength- 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 byteslength- use input bytes up to specified lengthtmp- 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 streambuffer- 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)
-
registerWriterFactory
public boolean registerWriterFactory(DslJson.ConverterFactory<? extends JsonWriter.WriteObject> factory)
-
registerReaderFactory
public boolean registerReaderFactory(DslJson.ConverterFactory<? extends JsonReader.ReadObject> factory)
-
registerBinderFactory
public boolean registerBinderFactory(DslJson.ConverterFactory<? extends JsonReader.BindObject> factory)
-
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 instanceTypes 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- typeS- type or subtype- Parameters:
manifest- specified typereader- 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 instanceTypes 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 typereader- 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- typeS- type or subtype- Parameters:
manifest- specified typebinder- 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 typebinder- 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 typewriter- 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 typewriter- 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:
tryFindReaderin interfaceTypeLookup- 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:
tryFindBinderin interfaceTypeLookup- 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)
-
probeForObjectReader
@Nullable private JsonReader.ReadJsonObject<JsonObject> probeForObjectReader(java.lang.Class<?> manifest, java.lang.Object instance)
-
getObjectReader
@Nullable protected final JsonReader.ReadJsonObject<JsonObject> getObjectReader(java.lang.Class<?> manifest)
-
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 readerinput- 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 typebody- input JSONsize- 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 typebody- input JSONsize- 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 typebody- input JSONsize- 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 typestream- input JSONbuffer- 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 typestream- 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 typestream- input JSONbuffer- 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 typestream- 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 typestream- input JSONbuffer- 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 typestream- 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 infostream- 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 infostream- JSON data streambuffer- 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
-
convertToReader
private <T extends JsonObject> JsonReader.ReadObject<T> convertToReader(JsonReader.ReadJsonObject<T> decoder)
-
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.IOExceptionStreaming 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 datastream- target JSON streamwriter- 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.IOExceptionStreaming 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 datamanifest- type of elements in collectionstream- target JSON streamwriter- 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- writerarray- 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- writerarray- itemslen- 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- writerlist- 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- writercollection- 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 JSONmanifest- type manifestvalue- 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 serializestream- 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:
serializein interfaceUnknownSerializer- Parameters:
writer- where to write resulting JSONvalue- object instance to serialize- Throws:
java.io.IOException- error when unable to serialize instance
-
-