GithubHelp home page GithubHelp logo

elektro-wolle / jackson-module-kotlin Goto Github PK

View Code? Open in Web Editor NEW

This project forked from fasterxml/jackson-module-kotlin

0.0 1.0 0.0 758 KB

Module that adds support for serialization/deserialization of Kotlin (http://kotlinlang.org) classes and data classes.

License: Apache License 2.0

Kotlin 96.39% Java 0.60% Logos 3.02%

jackson-module-kotlin's Introduction

Kotlin CircleCI Kotlin Slack

Overview

Module that adds support for serialization/deserialization of Kotlin classes and data classes. Previously a default constructor must have existed on the Kotlin object for Jackson to deserialize into the object. With this module, single constructor classes can be used automatically, and those with secondary constructors or static factories are also supported.

Status

2.9.8+ Releases are compiled with Kotlin 1.3.x, other older releases are Kotlin 1.2.x. All should be compatible with current Kotlin if you also ensure the kotlin-reflect dependency is included with the same version number as stdlib.

  • release 2.11.3 (for Jackson 2.11.x) CircleCI
  • release 2.10.5 (for Jackson 2.10.x)
  • release 2.9.10 (for Jackson 2.9.x)

Releases require that you have included Kotlin stdlib and reflect libraries already.

Gradle:

implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.+"

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
    <version>2.11.3</version>
</dependency>

Usage

For any Kotlin class or data class constructor, the JSON property names will be inferred from the parameters using Kotlin runtime type information.

To use, just register the Kotlin module with your ObjectMapper instance:

val mapper = ObjectMapper().registerModule(KotlinModule())
// or with 2.10 and later
val mapper = JsonMapper.builder().addModule(KotlinModule()).build()

or with the extension functions imported from import com.fasterxml.jackson.module.kotlin.*, one of:

val mapper = jacksonObjectMapper()
val mapper = ObjectMapper().registerKotlinModule()

A simple data class example:

import com.fasterxml.jackson.module.kotlin.*

data class MyStateObject(val name: String, val age: Int)

...
val mapper = jacksonObjectMapper()

val state = mapper.readValue<MyStateObject>(json)
// or
val state: MyStateObject = mapper.readValue(json)
// or
myMemberWithType = mapper.readValue(json)

All inferred types for the extension functions carry in full generic information (reified generics). Therefore, using readValue() extension without the Class parameter will reify the type and automatically create a TypeReference for Jackson.

Annotations

You can intermix non-field values in the constructor and JsonProperty annotation in the constructor. Any fields not present in the constructor will be set after the constructor call. An example of these concepts:

   @JsonInclude(JsonInclude.Include.NON_EMPTY)
   class StateObjectWithPartialFieldsInConstructor(val name: String, @JsonProperty("age") val years: Int)    {
        @JsonProperty("address") lateinit var primaryAddress: String   // set after construction
        var createdDt: DateTime by Delegates.notNull()                // set after construction
        var neverSetProperty: String? = null                          // not in JSON so must be nullable with default
    }

Note that using lateinit or Delegates.notNull() will ensure that the value is never null when read, while letting it be instantiated after the construction of the class.

Caveats

  • The @JsonCreator annotation is optional unless you have more than one constructor that is valid, or you want to use a static factory method (which also must have platformStatic annotation, e.g. @JvmStatic). In these cases, annotate only one method as JsonCreator.
  • Serializing a member or top-level Kotlin class that implements Iterator requires a workaround, see Issue #4 for easy workarounds.
  • If using proguard:
    • kotlin.Metadata annotations may be stripped, preventing deserialization. Add a proguard rule to keep the kotlin.Metadata class: -keep class kotlin.Metadata { *; }
    • If you're getting java.lang.ExceptionInInitializerError, you may also need: -keep class kotlin.reflect.** { *; }

Support for Kotlin Built-in classes

These Kotlin classes are supported with the following fields for serialization/deserialization (and other fields are hidden that are not relevant):

  • Pair (first, second)
  • Triple (first, second, third)
  • IntRange (start, end)
  • CharRange (start, end)
  • LongRange (start, end)

(others are likely to work, but may not be tuned for Jackson)

Configuration

The Kotlin module may be given a few configuration parameters at construction time; see the inline documentation for details on what options are available and what they do.

val mapper = JsonMapper.builder()
        .addModule(KotlinModule(strictNullChecks = true))
        .build()

If your ObjectMapper is constructed in Java, there is a builder method provided for configuring these options:

KotlinModule kotlinModule = new KotlinModule.Builder()
        .strictNullChecks(true)
        .build();
ObjectMapper objectMapper = JsonMapper.builder()
        .addModule(kotlinModule)
        .build();

Development

Maintainers

Following developers have committer access to this project.

  • Author: Jayson Minard (@apatrida) wrote this module; still helps issues from time to time
  • Active Maintainers:
    • Drew Stephens (@dinomite)
    • Vyacheslav Artemyev (@viartemev)
  • Co-maintainers:
    • Tatu Saloranta (@cowtowncoder)

You may at-reference them as necessary but please keep in mind that all maintenance work is strictly voluntary (no one gets paid to work on this or any other Jackson components) so there is no guarantee for timeliness of responses.

All Pull Requests should be reviewed by at least one of active maintainers; bigger architectural/design questions should be agreed upon by majority of active maintainers (at this point meaning both Drew and Vyacheslav :) ).

Releases & Branches

This module follows the release schedule of the rest of Jackson—the current version is consistent across all Jackson components & modules. See the jackson-databind README for details.

jackson-module-kotlin's People

Contributors

6bangs avatar apatrida avatar christophgr avatar ciderale avatar cowtowncoder avatar danielthomas avatar davidrigglemaninin avatar dinomite avatar drizzd avatar eddsteel avatar frost13it avatar greyteardrop avatar hiddewie avatar jasperblues avatar kimond avatar kpdonn avatar lipatovandrey avatar manjunathms35 avatar miha-x64 avatar nightlynexus avatar numezmat avatar prb avatar shartte avatar simonrolin avatar stephanebg avatar tanabe avatar urielsalis avatar viartemev avatar wjur avatar yorlov avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.