High performance JVM JSON library

Overview

DSL-JSON library

Fastest JVM (Java/Android/Scala/Kotlin) JSON library with advanced compile-time databinding support. Compatible with DSL Platform.

Java JSON library designed for performance. Built for invasive software composition with DSL Platform compiler.

JVM serializers benchmark results

Distinguishing features

  • supports external schema - Domain Specification Language (DSL)
  • works on existing POJO classes via annotation processor
  • performance - faster than any other Java JSON library. On par with fastest binary JVM codecs
  • works on byte level - deserialization can work on byte[] or InputStream. It doesn't need intermediate char representation
  • extensibility - support for custom types, custom analyzers, annotation processor extensions...
  • streaming support - large JSON lists support streaming with minimal memory usage
  • zero-copy operations - converters avoid producing garbage
  • minimal size - runtime dependency weights around 200KB
  • no unsafe code - library doesn't rely on Java UNSAFE/internal methods
  • POJO <-> object and/or array format - array format avoids serializing names, while object format can be used in minimal serialization mode
  • legacy name mapping - multiple versions of JSON property names can be mapped into a single POJO using alternativeNames annotation
  • binding to an existing instance - during deserialization an existing instance can be provided to reduce GC
  • generics, builder pattern, factory pattern and ctor with arguments - Java8 version supports all relevant initialization methods
  • compile time detection of unsafe conversion - Java8 version can throw compile time error for conversion which can fail at runtime
  • advanced annotation processor support - support for Java-only compilation or DSL Platform integration via conversion of Java code to DSL schema
  • customizable runtime overheads - works in reflection mode, in Java8 annotation processor mode or DSL Platform mode. Schema and annotation based POJOs are prepared at compile time
  • support for other library annotations - Jackson and JsonB annotations will be used and compile time analysis can be extended in various ways
  • Scala types support - Scala collections, primitives and boxed primitives work without any extra annotations or configuration
  • Kotlin support - annotation processor can be used from Kotlin. NonNull annotation is supported
  • JsonB support - high level support for JsonB String and Stream API. Only minimal support for configuration

Schema based serialization

DSL can be used for defining schema from which POJO classes with embedded JSON conversion are constructed. This is useful in large, multi-language projects where model is defined outside of Java classes. More information about DSL can be found on DSL Platform website.

@CompiledJson annotation

Annotation processor works by analyzing Java classes and its explicit or implicit references. Processor outputs encoding/decoding code/descriptions at compile time. This avoids the need for reflection, provides compile time safety and allows for some advanced configurations. Processor can register optimized converters into META-INF/services. This will be loaded during DslJson initialization with ServiceLoader. Since v1.8.0 naming conventions will be used for Java8 converters (package._NAME_DslJsonConverter) which works even without loading services upfront. Converters will be created even for dependent objects which don't have @CompiledJson annotation. This can be used to create serializers for pre-existing classes without annotating them.

Java8 annotation processor

Since v1.7.0 DSL-JSON supports compile time databinding without Mono/.NET dependency. It provides most features and flexibility, due to integration with runtime analysis and combining of various generic analysis. Bean properties, public fields, classes without empty constructor, factories and builder patterns are supported. Package private classes and factory methods can be used. Array format can be used for efficient payload transfer.

To use Java8 annotation processor its sufficient to just reference Java8 version of the library:

<dependency>
  <groupId>com.dslplatform</groupId>
  <artifactId>dsl-json-java8</artifactId>
  <version>1.9.8</version>
</dependency>

For use in Android, Gradle can be configured with:

android {
  compileOptions {
    sourceCompatibility 1.8
    targetCompatibility 1.8
  }
}
dependencies {
  compile 'com.dslplatform:dsl-json-java8:1.9.8'
  annotationProcessor 'com.dslplatform:dsl-json-java8:1.9.8'
  provided 'javax.json.bind:javax.json.bind-api:1.0'
}

To use DSL-JSON on older Android versions setup should be done without initializing Java8 specific types:

private final DslJson<Object> dslJson = new DslJson<Object>(runtime.Settings.basicSetup());

DSL Platform annotation processor

DSL Platform annotation processor requires .NET/Mono to create databindings. It works by translating Java code into equivalent DSL schema and running DSL Platform compiler on it. Since v1.7.2 Java8 version has similar performance, so the main benefit is ability to target Java6. Bean properties, public non-final fields and only classes with empty constructor are supported. Only object format is supported.

If you are not sure which annotation processor to use, you should probably use the Java8 version instead of the DSL Platform one. DSL Platform annotation processor can be added as Maven dependency with:

<dependency>
  <groupId>com.dslplatform</groupId>
  <artifactId>dsl-json-processor</artifactId>
  <version>1.9.8</version>
  <scope>provided</scope>
</dependency>

For use in Android, Gradle can be configured with:

dependencies {
  compile 'com.dslplatform:dsl-json:1.9.8'
  annotationProcessor 'com.dslplatform:dsl-json-processor:1.9.8'
}

Project examples can be found in examples folder

Java/DSL property mapping

Java type DSL type Java type DSL type
int int byte[] binary
long long java.util.Map<String,String> properties?
float float java.net.InetAddress ip?
double double java.awt.Color color?
boolean bool java.awt.geom.Rectangle2D rectangle?
java.lang.String string? java.awt.geom.Point2D location?
java.lang.Integer int? java.awt.geom.Point point?
java.lang.Long long? java.awt.image.BufferedImage image?
java.lang.Float float? android.graphics.Rect rectangle?
java.lang.Double double? android.graphics.PointF location?
java.lang.Boolean bool? android.graphics.Point point?
java.math.BigDecimal decimal? android.graphics.Bitmap image?
java.time.LocalDate date? org.w3c.dom.Element xml?
java.time.OffsetDateTime timestamp? org.joda.time.LocalDate date?
java.util.UUID uuid? org.joda.time.DateTime timestamp?

Java/DSL collection mapping

Java type DSL type
array Array
java.util.List List
java.util.Set Set
java.util.LinkedList Linked List
java.util.Queue Queue
java.util.Stack Stack
java.util.Vector Vector
java.util.Collection Bag

Collections can be used on supported Java types, other POJOs and enums.

Other collections/containers

Java8 supports all kinds of collections, even maps and Java8 specific container such as Optional.

Custom types in compile-time databinding

Types without builtin mapping can be supported in three ways:

  • by implementing JsonObject and appropriate JSON_READER
  • by defining custom conversion class and annotating it with @JsonConverter
  • by defining custom conversion class and referencing it from property with converter through @JsonAttribute

Custom converter for java.util.Date can be found in example project Annotation processor will check if custom type implementations have appropriate signatures. Converter for java.util.ArrayList can be found in same example project

@JsonConverter which implements Configuration will also be registered in META-INF/services which makes it convenient to setup initialization.

All of the above custom type examples work out-of-the-box in Java8 version of the library.

@JsonAttribute features

DSL-JSON property annotation supports several customizations/features:

  • name - define custom serialization name
  • alternativeNames - different incoming JSON attributes can be mapped into appropriate property. This can be used for simple features such as casing or for complex features such as model evolution
  • ignore - don't serialize specific property into JSON
  • nullable - tell compiler that this property can't be null. Compiler can remove some checks in that case for minuscule performance boost
  • mandatory - mandatory properties must exists in JSON. Even in omit-defaults mode. If property is not found, IOException will be thrown
  • index - defines index order used during serialization or can be used for array format
  • hashMatch - DSL-JSON matches properties by hash values. If this option is turned off exact comparison will be performed which will add minor deserialization overhead, but invalid properties with same hash names will not be deserialized into "wrong" property. In case when model contains multiple properties with same hash values, compiler will inject exact comparison by default, regardless of this option value.
  • converter - custom conversion per property. Can be used for formatting or any other custom handling of JSON processing for specific property
  • typeSignature - disable inclusion of $type during abstract type serialization. By default abstract type will include additional information which is required for correct deserialization. Abstract types can be deserialized into a concreted type by defining deserializeAs on @CompiledJson which allows the removal of $type during both serialization and deserialization

@JsonValue enum feature

Java8 version supports converting enum as custom value. To use such feature @JsonValue annotation must be placed on method or field.

JSON pretty print

Formatted output with alignments and newlines can be created via PrettifyOutputStream.

dslJson.serialize(instance, new PrettifyOutputStream(outputStream));

External annotations

For existing classes which can't be modified with @JsonAttribute alternative external annotations are supported:

Nullability annotations

During translation from Java objects into DSL schema, existing type system nullability rules are followed. With the help of non-null annotations, hints can be introduced to work around some Java nullability type system limitations. List of supported non-null annotations can be found in processor source code

Property aliases

Annotation processor supports external annotations for customizing property name in JSON:

  • com.fasterxml.jackson.annotation.JsonProperty
  • com.google.gson.annotations.SerializedName

Those annotations will be translated into specialized DSL for specifying serialization name.

Ignored properties

Existing bean properties and fields can be ignored using one of the supported annotations:

  • com.fasterxml.jackson.annotation.JsonIgnore
  • org.codehaus.jackson.annotate.JsonIgnore

Ignored properties will not be translated into DSL schema.

Required properties

Jackson required = true can be used to fail if property is missing in JSON:

Serialization modes

Library has several serialization modes:

  • minimal serialization - omits default properties which can be reconstructed from schema definition
  • all properties serialization - will serialize all properties from schema definition
  • array format - object will be serialized as array without property names

Best serialization performance can be obtained with combination of minimal serialization and minified property names/aliases or array format. Object and array formats can be combined. POJO can support both formats at once.

Benchmarks

Independent benchmarks can validate the performance of DSL-JSON library:

Reference benchmark (built by library authors):

Dependencies

Core library (with analysis processor) and DSL Platform annotation processor targets Java6. Java8 library includes runtime analysis, reflection support, annotation processor and Java8 specific types. When Java8 annotation processor is used Mono/.NET doesn't need to be present on the system. Android can use Java8 version of the library even on older versions due to lazy loading of types which avoids loading types Android does not support.

If not sure which version to use, use Java8 version of the library with annotation processor.

Runtime analysis

Java8 library has builtin runtime analysis support, so library can be used even without compile time databinding or it can just add additional runtime support alongside compile-time databinding (default behavior). Runtime analysis is required for some features such as generics which are not known at compile time. Runtime analysis works by lazy type resolution from registered converters, eg:

private final DslJson.Settings settings = runtime.Settings.withRuntime().includeServiceLoader();
private final DslJson<Object> json = new DslJson<Object>(settings);

Best practices

Reusing reader/writer.

JsonWriter It has two modes of operations:

  • populating the entire output into byte[]
  • targeting output stream and flushing local byte[] to target output stream

JsonWriter can be reused via reset methods which binds it to specified target. When used directly it should be always created via newWriter method on DslJson instance. Several DslJson serialize methods will reuse the writer via thread local variable. When using JsonWriter via the first mode, result can be copied to stream via .toStream(OutputStream) method.

DslJson<Object> json = ... // always reuse
OutputStream stream = ... // stream with JSON in UTF-8
json.serialize(pojo, stream); //will use thread local writer

JsonReader can process byte[] or InputStream inputs. It can be reused via the process methods. When calling DslJson deserialize methods often exists in two flavors:

  • with byte[] argument, in which case a new JsonReader will be created, but for best performance byte[] should be reused
  • without byte[] argument in which case thread local reader will be reused

For small messages it's better to use byte[] API. When reader is used directly it should be always created via newReader method on DslJson instance.

DslJson<Object> json = ... // always reuse
InputStream stream = ... // stream with JSON in UTF-8
POJO instance = json.deserialize(POJO.class, stream); //will use thread local reader

Binding

JsonReader has iterateOver method for exposing input collection as consumable iterator. Also, since v1.5 binding API is available which can reuse instances for deserialization.

DslJson<Object> json = new DslJson<Object>(); //always reuse
byte[] bytes = "{\"number\":123}".getBytes("UTF-8");
JsonReader<Object> reader = json.newReader().process(bytes, bytes.length);
POJO instance = new POJO(); //can be reused
POJO bound = reader.next(POJO.class, instance); //bound is the same as instance above

Limits

Library has various configurable limits built-in to protect against malicious input:

  • default of 512 digits
  • default of 128MB strings

String API

DSL-JSON works on byte level. To discourage use of String for JSON processing there is no high level String API. If one really needs to use String, manual conversion is required.

DslJson<Object> json = new DslJson<Object>();
byte[] bytes = "{\"number\":123}".getBytes("UTF-8"); //convert string to UTF-8 bytes
POJO instance = json.deserialize(POJO.class, bytes, bytes.length);
ByteArrayOutputStream os = new ByteArrayOutputStream();
json.serialize(instance, os);
String outputAsString = os.toString("UTF-8"); //convert stream to string

Scala support

Scala types can be used. They will be analyzed at runtime with. Scala specific behaviour:

  • Option[_] - means that JSON attribute can be null. If type is not an Option and null is found, IOException will be thrown
  • Container[Primitive] - eg: Option[Int] - will behave as Option<int> and thus it will avoid wrong type decoding issues
  • name: Type = Default - will be used to imply if attribute can be omitted from JSON - in which case the specified default value will be used (default values are static at analysis time)
  • tuples - will be encoded/decoded in Array format (without property names)

To avoid some Java/Scala conversion issues it's best to use Scala specific API via

import com.dslplatform.json._ // import pimping
val dslJson = new DslJson[Any]()
//use encode pimp to correctly analyze types (this will mostly provide some performance benefits)
dslJson.encode(instance, ...)
//use decode pimp to correctly analyze types (this will avoid some issues with nested classes and missing metadata)
val result = dslJson.decode[TargetType](...) 

For SBT dependency can be added as:

libraryDependencies += "com.dslplatform" %% "dsl-json-scala" % "1.9.8"

Kotlin support

Kotlin has excellent Java interoperability, so annotation processor can be used as-is. When used with Gradle, configuration can be done via:

apply plugin: 'kotlin-kapt'
dependencies {
  compile "com.dslplatform:dsl-json-java8:1.9.8"
  kapt "com.dslplatform:dsl-json-java8:1.9.8"
}

FAQ

Q: What is TContext in DslJson and what should I use for it?
A: Generic TContext is used for library specialization. Use DslJson<Object> when you don't need it and just provide null for it.

Q: Why is DSL-JSON faster than others?
A: Almost zero allocations. Works on byte level. Better algorithms for conversion from byte[] -> type and vice-versa. Minimized unexpected branching. Reflection version is comparable with Jackson performance. Extra difference comes from compile-time databinding.

Q: DslJson is failing with unable to resolve reader/writer. What does it mean?
A: During startup DslJson loads services through ServiceLoader. For this to work META-INF/services/com.dslplatform.json.Configuration must exist with the content of dsl_json_Annotation_Processor_External_Serialization or dsl_json.json.ExternalSerialization which is the class crated during compilation step. Make sure you've referenced processor library (which is responsible for setting up readers/writers during compilation) and double check if annotation processor is running. Refer to example projects for how to set up environment. As of v1.8.0 Java8 version of the library avoids this issue since services are not used by default anymore in favor of named based convention. Eclipse is known to create problems with annotation processor since it requires manual setup (instead of using pom.xml setup). For Eclipse the best workaround is to build with Maven instead or relying on its build tools.

Q: Maven/Gradle are failing during compilation with @CompiledJson when I'm using DSL Platform annotation processor. What can I do about it?
A: If Mono/.NET is available it should work out-of-the-box. But if some strange issue occurs, detailed log can be enabled to see what is causing the issue. Log is disabled by default, since some Gradle setups fail if something is logged during compilation. Log can be enabled with dsljson.loglevel processor option

Q: DSL Platform annotation processor checks for new DSL compiler version on every compilation. How can I disable that?
A: If you specify custom dsljson.compiler processor option or put dsl-compiler.exe in project root it will use that one and will not check online for updates

Q: I get compilation error when annotation procesor runs. What can I do?
A: Common error is missing dependency on Java 9+ for annotation marker. You can add such dependency on configure compiler arguments to exclude it via dsljson.generatedmarker. Otherwise its best to inspect the generated code, look if there is some configuration error, like referencing class without sufficient visibility. If there is nothing wrong with the setup, there might be a bug with the DSL-JSON annotation processor in which case it would be helpful to provide a minimal reproducible

Q: What is this DSL Platform?
A: DSL Platform is a proprietary compiler written in C#. Since v1.7.0 DSL Platform is no longer required to create compile-time databinding. Compiler is free to use, but access to source code is licensed. If you want access to the compiler or need performance consulting let us know

Comments
  • Lombok setter property AccessLevel.NONE is not working.

    Lombok setter property AccessLevel.NONE is not working.

    HI ,

    `@Getter @Setter @NoArgsConstructor @AllArgsConstructor @CompiledJson public class TestList {

    @JsonProperty("test_name") @Setter(AccessLevel.NONE) private List list = new ArrayList<>(); }`

    and model class

    `public Class Model {

    @JsonProperty("test_field1") @Setter(AccessLevel.NONE) private String field1;

    }`

    1. when I am trying to serialize/deserialze , its not working for list. 2.Similar issue can be observed if only single field is having @Setter(AccessLevel.NONE) then I am not able to deserialise that property (field1).

    Version - com.dslplatform dsl-json-java8 1.9.6

    Thank you very much , I am trying to implement DSL because I have observed the speed compare to other libraries.

    opened by prasannajoshi2121 35
  • Support builder classes for immutable objects

    Support builder classes for immutable objects

    I would like to add dsl-json support to https://github.com/soabase/soabase-halva/blob/master/halva/src/main/java/io/soabase/halva/caseclass/README.md . halva generates immutable classes that are paired with builder classes. Jackson support for the builder pattern can be implemented with @JsonDeserialize.

    Example: https://github.com/soabase/soabase-halva/blob/master/examples/example-generated/JsonTestCase.java

    Is there an equivalent way to specify a custom builder object with dsl-json? Default compilation results in:

    CompiledJson requires accessible public no argument constructor, therefore 'com.dslplatform.maven.Example.ExampleCase' requires public no argument constructor
    
    enhancement help wanted 
    opened by azell 29
  • Add support for serializing java.lang.Object fields in classes annotated with @CompiledJson

    Add support for serializing java.lang.Object fields in classes annotated with @CompiledJson

    Currently if class contains field of Object type, then DslJson unable to find writer for such field. e.g:

    @CompiledJson
    class Model {
        public String key;
        public Object value;
    }
    
    opened by varahash 18
  • Add support for runtime analysis at Java 6

    Add support for runtime analysis at Java 6

    This will allow use reflection data binding on platform which currently does not support Java8 (e.g. Android prior API 24).

    I propose to move appropriate classes from 'dsl-json-java8' module to core module 'dsl-json' or we can create new one 'dsl-json-reflection'.

    It seems relatively easy to do. We just need to replace usage of 'java.lang.function.*' with our custom interfaces. And keep ImmutableAnalyzer class in 'dsl-json-java8' module, since parameter names are not supported prior Java8.

    opened by varahash 17
  • java.io.IOException when deserialising to class

    java.io.IOException when deserialising to class

    Hi,

    I'm using Kotlin 1.3 and have a rather simple setup that's not working:

    @CompiledJson
    data class GraphQLRequest(val id: String? = null, val query: String = "", val variables: Map<String,Any> = emptyMap(), val operationName: String? = null)
    
    val dslJson = DslJson<Any>(Settings.withRuntime<Any>().includeServiceLoader())
    
    val jsonInputStream = "{\"query\":\"mutation T(\$input: [DocumentInput]) {createDocument(input: \$input) {name,id}}\",\"variables\":{\"input\":[{\"name\":\"doc1\"},{\"name\":\"doc2\"}]},\"operationName\":\"T\"}".byteInputStream(Charsets.UTF_8)
    //val mapVal = dslJson.deserialize(Map::class.java, jsonInputStream)
    val gqlRequestVal = dslJson.deserialize(GraphQLRequest::class.java, jsonInputStream)
    
    

    Deserialising to a Map (the commented mapVal line works) but deserialising to GraphQLRequest (as in the last line) results in: java.io.IOException: Expecting '}' at position: 3, following: `{"q`, before: `uery":"mutation T($i`. Found q

    I'm sure I've done something wrong but I can't figure out what, any pointers would be really helpful.

    opened by emrul 16
  • Feature Request: Register Interfaces on ExternalSerialization#setup

    Feature Request: Register Interfaces on ExternalSerialization#setup

    opened by jpe42 16
  • Uppercase keys cause JSON de-seralisation issues

    Uppercase keys cause JSON de-seralisation issues

    package application
    
    import com.dslplatform.json.CompiledJson
    import com.dslplatform.json.DslJson
    import com.dslplatform.json.JsonAttribute
    import com.dslplatform.json.runtime.Settings
    
    @CompiledJson
    data class Response(@JsonAttribute(name = "QueryResult") val queryResult: QueryResult?)
    
    data class QueryResult(@JsonAttribute(name = "PageSize") val pageSize: Int?)
    
    fun main(args: Array<String>) {
        //include service loader will load up classes created via annotation processor
        val dslJson = DslJson<Any>(Settings.withRuntime<Any>().includeServiceLoader())
    
        val jsonNotWorking = "{\"QueryResult\": {\"PageSize\": 200}}"
        println(dslJson.deserialize(Response::class.java, jsonNotWorking.byteInputStream()))
    
        val jsonWorking = "{\"queryResult\": {\"pageSize\": 200}}"
        println(dslJson.deserialize(Response::class.java, jsonWorking.byteInputStream()))
    }
    

    Output

    Response(queryResult=null)
    Response(queryResult=QueryResult(pageSize=200))
    

    Using the above example, when the JSON contains CamelCase keys the JSON de-serialisation fails.

    bug 
    opened by lwis 13
  • Support for deseralization with no type information.

    Support for deseralization with no type information.

    Jackson will default to using LinkedHashMap to represent JSON where there is no type information given, or the type information is given as Object.class.

    Is there any support for this type of behaviour with dsl-json?

    I am looking to deserialize json where a field may have varying types. For example, in my model class I have an instance variable declared as Map<String, Object> fieldName. The object value may be represented in the JSON as a string, int, object or array etc. Does dsl-json support a method of generically deserializing this into some sort of structure so it can be accessed from the instance variable.

    Here is an example of some JSON that I hope to deserialize into a Map<String, Object>

     "fieldName": {
                "alwaysString": {
                    "fieldInsideObject": 5
                },
                "anotherString": 40
            }
    

    Thanks

    opened by JakeAngell 13
  • string converted into number parsing numbers

    string converted into number parsing numbers

    Hi,

    doing some testing, a special case called my attention. The methods to deserialize into numbers from the class NumberConverter, don't return an error when the number is a string, I mean:

    {"a" : "1"}

    NumberConverter.deserializeInt()

    would parse and convert "1" into 1. From my point of view, it should return an error, or at least, it would be nice to pass over that decision to the client, because it's not clear that it is the expected behavior.

    The case mentioned above can be even worse in the following scenario {"a": "0001"} because all the leading zeros are dropped, returning the integer 1

    Any ideas or suggestions?

    Thanks in advance

    opened by imrafaelmerino 12
  • java.lang.IllegalArgumentException: argument type mismatch

    java.lang.IllegalArgumentException: argument type mismatch

    Code to reproduce:

    import com.dslplatform.json.{DslJson, DslJsonScala}
    
    case class V(
                  text: String,
                  value: Int)
    
    case class ES(
                   distance: V,
                   duration: V,
                   status: String)
    
    case class RS(elements: IndexedSeq[ES])
    
    case class DM(
                   destination_addresses: IndexedSeq[String],
                   origin_addresses: IndexedSeq[String],
                   rows: IndexedSeq[RS],
                   status: String)
    
    
    val dslJson = new DslJson[Any](Settings.withRuntime().`with`(new ConfigureScala))
    val dslJsonScala = new DslJsonScala(dslJson)
    val decoder = dslJsonScala.decoder[DM]
    val reader = dslJson.newReader()
    val bytes = "{\"destination_addresses\":[],\"origin_addresses\":[],\"rows\":[],\"status\":\"OK\"}".getBytes
    reader.process(bytes, bytes.length)
    reader.read()
    println(decoder.read(reader))
    
    opened by plokhotnyuk 12
  • Unable to serialize generics in Scala

    Unable to serialize generics in Scala

    I have been unable to serialize a generic class using GenericTest as reference. I have below a very simple class in Scala. To imitate the Java test code I don't use Option or case class.

      @CompiledJson
      class Abc[A] {
        var test: A = _
      }
    
      val dslJson = new DslJson[Any](new DslJson.Settings()
                    .allowArrayFormat(true).includeServiceLoader())
      val writer = dslJson.newWriter
      var model = new Abc[String]
      model.test = "aaa"
      val t = new TypeDefinition[Abc[String]]() {}.`type`
      val os = new ByteArrayOutputStream
      writer.reset(os)
      val res = dslJson.serialize(writer, t, model)     
      writer.flush()
    

    res always returns false signifying failed serialization. Perhaps you could help point out the problem ? Thank you.

    opened by inmyth 12
  • Bump hsqldb from 2.3.4 to 2.7.1 in /java8

    Bump hsqldb from 2.3.4 to 2.7.1 in /java8

    Bumps hsqldb from 2.3.4 to 2.7.1.

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Support kotlin inline classes

    Support kotlin inline classes

    Kotlin has a nice feature inline classes. Let's assume that we have a class which stores a price in cents (2 digits precision) Currently I do something like (quite hacky), but it causes long boxing:

    @JvmInline
    value class Decimal2(val raw: Long)
    
    class Event {
        @JsonAttribute(converter = Decimal2Converter.RawConverter::class)
        @set:JvmName("price")
        @get:JvmName("price")
        var price: Decimal2 = DEC2_ZERO
    }
    

    Input json example: {"price": 1.29}, would be transformed into Decimal(129)

    It would be nice to have first-citizen support for kotlin inline classes

    opened by vans239 16
  • [POC] add nested bindings

    [POC] add nested bindings

    Inspired by https://github.com/ngs-doo/dsl-json/issues/240

    Background

    bind feature helps a lot to minimise allocations. Unfortunately, bind currently works only for top-level object. Nested objects are created using JSON_READER (which causes allocations). It would be great to be able to bind nested objects and still benefit from auto-generated binder for top-level

    Changes

    Add partial/inital support of nested binding.

    Notes

    1. there is no way to force user to initialise field in the top-level object
    2. writer/reader must be defined to use binder

    I consider the PR as POC, so proposal can be redesigned based on the feedback.

    opened by vans239 0
  • StackOverflowError in the preprocessor when generating converters via @CompiledJson

    StackOverflowError in the preprocessor when generating converters via @CompiledJson

    Hi,

    Thank you very much for creating and maintaining this fantastic library!

    I am getting a stack overflow error in some cases when using the @CompiledJson annotation.

    Error:

    ...
    Caused by: java.lang.StackOverflowError
    	at java.base/java.lang.String.valueOf(String.java:2951)
    	at java.base/java.lang.StringBuilder.append(StringBuilder.java:168)
    	at jdk.compiler/com.sun.tools.javac.util.List.toString(List.java:326)
    	at jdk.compiler/com.sun.tools.javac.util.List.toString(List.java:339)
    	at jdk.compiler/com.sun.tools.javac.code.Type$ClassType.toString(Type.java:1027)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:179)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:203)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:188)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:203)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:188)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:203)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:188)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:203)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:188)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:203)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:188)
    	at com.dslplatform.json.processor.AttributeInfo.createTypeSignature(AttributeInfo.java:203)
    ...
    

    We are using Java 11 and the minimal repro for this is:

    package foo;
    
    import com.dslplatform.json.CompiledJson;
    
    @CompiledJson
    public class GenericClass<T> implements Comparable<GenericClass<T>> {
    
        final T genericField;
    
        public GenericClass(T genericField) {
            this.genericField = genericField;
        }
    
        public final T getGenericField() {
            return genericField;
        }
    
        @Override
        public int compareTo(GenericClass<T> other) {
            return 1;
        }
    }
    

    Any help with this would be appreciated!

    opened by vrasidas-at-b2c2 4
  • error

    error

    using gson this working fine, but error using dsl-json

    {"id_user":"-1","nopol":"dfas","imei":"ds","phone":"ds","id_gpsbrand":"261","id_vhbrand":"","object_type":0,"icon":"car.png","install_date":"2022-12-30","guaranty_date":"2022-12-21"}
    
    

    error

    om.dslplatform.json.ParsingException: Expecting '"' for string start. Found 0 at position: 107, following: `":"","object_type":0`, before: `,"icon":"car.png","i`
    	at com.dslplatform.json.ParsingException.create(ParsingException.java:16)
    	at com.dslplatform.json.JsonReader.newParseError(JsonReader.java:420)
    	at com.dslplatform.json.JsonReader.newParseError(JsonReader.java:408)
    	at com.dslplatform.json.JsonReader.parseString(JsonReader.java:642)
    	at com.dslplatform.json.JsonReader.readString(JsonReader.java:624)
    	at com.dslplatform.json.StringConverter$1.read(StringConverter.java:15)
    	at com.dslplatform.json.StringConverter$1.read(StringConverter.java:10)
    
    opened by centratelemedia 1
  • Support for nested binding

    Support for nested binding

    I am interested in ability to bind exisiting instance recursively. Based on my understanding of source code the feature currently is not supported

    Kotlin example

    @CompiledJson
    class Container {
        var a: String = "a"
        var b: String = "c"
        var c: String = "b"
    }
    
    @CompiledJson
    class Example {
        var value: Int = 1
        var container: Container = Container()
    }
    

    Example_DslJsonConverter contains something like:

    public void bindContent(...){
    			...
    			instance.setValue(com.dslplatform.json.NumberConverter.deserializeInt(reader));
    			...
    			instance.setContainer(reader_container().read(reader));
    			
    }
    

    Instead I'd like to have:

    public void bindContent(...){
    			...
    			instance.setValue(com.dslplatform.json.NumberConverter.deserializeInt(reader));
    			...
                            binder_container().bind(reader, instance.getContainer())
    }
    

    That way instance reading would be zero allocation (mostly)

    opened by vans239 9
Owner
New Generation Software Ltd
New Generation Software Ltd
High performance JVM JSON library

DSL-JSON library Fastest JVM (Java/Android/Scala/Kotlin) JSON library with advanced compile-time databinding support. Compatible with DSL Platform. Ja

New Generation Software Ltd 835 Jan 2, 2023
A 250 lines single-source-file hackable JSON deserializer for the JVM. Reinventing the JSON wheel.

JSON Wheel Have you ever written scripts in Java 11+ and needed to operate on some JSON string? Have you ever needed to extract just that one deeply-n

Roman Böhm 14 Jan 4, 2023
High-performance JSON parser

HikariJSON A High-performance JSON parser. HikariJSON is targeted exclusively at Java 8. If you need legacy support, there are several decent librarie

Brett Wooldridge 454 Dec 31, 2022
JSON to JSON transformation library written in Java.

Jolt JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document. Useful For Transformin

Bazaarvoice 1.3k Dec 30, 2022
Generate Java types from JSON or JSON Schema and annotates those types for data-binding with Jackson, Gson, etc

jsonschema2pojo jsonschema2pojo generates Java types from JSON Schema (or example JSON) and can annotate those types for data-binding with Jackson 2.x

Joe Littlejohn 5.9k Jan 5, 2023
Essential-json - JSON without fuss

Essential JSON Essential JSON Rationale Description Usage Inclusion in your project Parsing JSON Rendering JSON Building JSON Converting to JSON Refer

Claude Brisson 1 Nov 9, 2021
A simple java JSON deserializer that can convert a JSON into a java object in an easy way

JSavON A simple java JSON deserializer that can convert a JSON into a java object in an easy way. This library also provide a strong object convertion

null 0 Mar 18, 2022
A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order

Read me first The current version of this project is licensed under both LGPLv3 (or later) and ASL 2.0. The old version (2.0.x) was licensed under LGP

Java Json Tools 1.5k Jan 4, 2023
A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a

Google 21.7k Jan 8, 2023
Screaming fast JSON parsing and serialization library for Android.

#LoganSquare The fastest JSON parsing and serializing library available for Android. Based on Jackson's streaming API, LoganSquare is able to consiste

BlueLine Labs 3.2k Dec 18, 2022
A modern JSON library for Kotlin and Java.

Moshi Moshi is a modern JSON library for Android and Java. It makes it easy to parse JSON into Java objects: String json = ...; Moshi moshi = new Mos

Square 8.7k Dec 31, 2022
Sawmill is a JSON transformation Java library

Update: June 25, 2020 The 2.0 release of Sawmill introduces a breaking change to the GeoIpProcessor to comply with the updated license of the MaxMind

Logz.io 100 Jan 1, 2023
Genson a fast & modular Java <> Json library

Genson Genson is a complete json <-> java conversion library, providing full databinding, streaming and much more. Gensons main strengths? Easy to use

null 212 Jan 3, 2023
Lean JSON Library for Java, with a compact, elegant API.

mJson is an extremely lightweight Java JSON library with a very concise API. The source code is a single Java file. The license is Apache 2.0. Because

Borislav Iordanov 77 Dec 25, 2022
A JSON Transmission Protocol and an ORM Library for automatically providing APIs and Docs.

?? 零代码、热更新、全自动 ORM 库,后端接口和文档零代码,前端(客户端) 定制返回 JSON 的数据和结构。 ?? A JSON Transmission Protocol and an ORM Library for automatically providing APIs and Docs.

Tencent 14.4k Dec 31, 2022
A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back

A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back, with a transparent support of any kind of self-references and with a full Java 9 compatibility.

Andrey Mogilev 9 Dec 30, 2021
Elide is a Java library that lets you stand up a GraphQL/JSON-API web service with minimal effort.

Elide Opinionated APIs for web & mobile applications. Read this in other languages: 中文. Table of Contents Background Documentation Install Usage Secur

Yahoo 921 Jan 3, 2023
JSON Library for Java with a focus on providing a clean DSL

JSON Library for Java with a focus on providing a clean DSL

Vaishnav Anil 0 Jul 11, 2022
A fast JSON parser/generator for Java.

fastjson Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON str

Alibaba 25.1k Dec 31, 2022