• Stars
    star
    1,123
  • Rank 41,432 (Top 0.9 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Kotlin 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

  • release 2.15.1 (for Jackson 2.15.x) GitHub Actions build
  • release 2.14.3 (for Jackson 2.14.x) GitHub Actions build
  • release 2.13.5 (for Jackson 2.13.x) GitHub Actions build

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

Gradle:

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

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
    <version>2.15.1</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:

// With Jackson 2.12 and later
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
...
val mapper = jacksonObjectMapper()
// or
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
...
val mapper = ObjectMapper().registerKotlinModule()
// or
import com.fasterxml.jackson.module.kotlin.jsonMapper
import com.fasterxml.jackson.module.kotlin.kotlinModule
...
val mapper = jsonMapper {
  addModule(kotlinModule())
}
Jackson versions prior to 2.10–2.11
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
...
val mapper = JsonMapper.builder().addModule(KotlinModule()).build()
Jackson versions prior to 2.10
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
...
val mapper = ObjectMapper().registerModule(KotlinModule())

A simple data class example:

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue

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.

Also, there are some convenient operator overloading extension functions for JsonNode inheritors.

import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import com.fasterxml.jackson.module.kotlin.*

// ...
val objectNode: ObjectNode = JsonNodeFactory.instance.objectNode()
objectNode.put("foo1", "bar").put("foo2", "baz").put("foo3", "bax")
objectNode -= "foo1"
objectNode -= listOf("foo2")
println(objectNode.toString()) // {"foo3":"bax"}

// ...
val arrayNode: ArrayNode = JsonNodeFactory.instance.arrayNode()
arrayNode += "foo"
arrayNode += true
arrayNode += 1
arrayNode += 1.0
arrayNode += "bar".toByteArray()
println(arrayNode.toString()) // ["foo",true,1,1.0,"YmFy"]

Compatibility

(NOTE: incomplete! Please submit corrections/additions via PRs!)

Different kotlin-core versions are supported by different Jackson Kotlin module minor versions. Here is an incomplete list of supported versions:

  • Jackson 2.15.x: Kotlin-core 1.5 - 1.8
  • Jackson 2.14.x: Kotlin-core 1.4 - 1.8
  • Jackson 2.13.x: Kotlin-core 1.4 - 1.7

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.** { *; }
    • If you're still running into problems, you might also need to add a proguard keep rule for the specific classes you want to (de-)serialize. For example, if all your models are inside the package com.example.models, you could add the rule -keep class com.example.models.** { *; }

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)

Sealed classes without @JsonSubTypes

Subclasses can be detected automatically for sealed classes, since all possible subclasses are known at compile-time to Kotlin. This makes com.fasterxml.jackson.annotation.JsonSubTypes redundant. A com.fasterxml.jackson.annotation.@JsonTypeInfo annotation at the base-class is still necessary.

  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
  sealed class SuperClass{
      class A: SuperClass()
      class B: SuperClass()
  }

...
val mapper = jacksonObjectMapper()
val root: SuperClass = mapper.readValue(json)
when(root){
    is A -> "It's A"
    is B -> "It's B"
}

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 kotlinModule = KotlinModule.Builder()
    .enable(KotlinFeature.StrictNullChecks)
    .build()
val mapper = JsonMapper.builder()
    .addModule(kotlinModule)
    .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 originally (no longer active)
  • Active Maintainers:
    • Dmitry Spikhalskiy (@Spikhalskiy) -- since 2.14
    • Drew Stephens (@dinomite)
    • Vyacheslav Artemyev (@viartemev)
    • WrongWrong (@k163377) -- since 2.15
  • Co-maintainers:
    • Tatu Saloranta (@cowtowncoder)

You may at-reference maintainers 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.

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.

Contributing

We welcome any contributionsβ€”reports of issues, ideas for enhancements, and pull requests related to either of those.

See the main Jackson contribution guidlines for more details.

Branches

If you are going to write code, choose the appropriate base branch:

  • 2.14 for bugfixes against the current stable version
  • 2.15 for additive functionality & features or minor, backwards compatible changes to existing behavior to be included in the next minor version release
  • master for significant changes to existing behavior, which will be part of Jackson 3.0

Failing tests

There are a number of tests for functionality that is broken, mostly in the failing package but a few as part of other test suites. Instead of ignoring these tests (with JUnit's @Ignore annotation) or excluding them from being run as part of automated testing, the tests are written to demonstrate the failure (either making a call that throws an exception or with an assertion that fails) but not fail the build, except if the underlying issue is fixed. This allows us to know when the tested functionality has been incidentally fixed by unrelated code changes.

See the tests readme for more information.

More Repositories

1

jackson

Main Portal page for the Jackson project
9,099
star
2

jackson-databind

General data-binding package for Jackson (2.x): works on streaming API (core) implementation(s)
Java
3,522
star
3

jackson-core

Core part of Jackson that defines Streaming API as well as basic shared abstractions
Java
2,263
star
4

jackson-annotations

Core annotations (annotations that only depend on jackson-core) for Jackson data processor
Java
1,029
star
5

jackson-docs

Documentation for the Jackson JSON processor.
727
star
6

jackson-dataformat-xml

Extension for Jackson JSON processor that adds support for serializing POJOs as XML (and deserializing from XML) as an alternative to JSON
Java
570
star
7

jackson-module-scala

Add-on module for Jackson (https://github.com/FasterXML/jackson) to support Scala-specific datatypes
Scala
501
star
8

jackson-dataformats-text

Uber-project for (some) standard Jackson textual format backends: csv, properties, yaml (xml to be added in future)
Java
405
star
9

jackson-modules-java8

Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)
Java
400
star
10

jackson-module-jsonSchema

Module for generating JSON Schema (v3) definitions from POJOs
Java
369
star
11

jackson-datatype-hibernate

Add-on module for Jackson JSON processor which handles Hibernate (https://www.hibernate.org/) datatypes; and specifically aspects of lazy-loading
Java
318
star
12

jackson-dataformats-binary

Uber-project for standard Jackson binary format backends: avro, cbor, ion, protobuf, smile
Java
313
star
13

aalto-xml

Ultra-high performance non-blocking XML processor (Stax API + extensions)
Java
292
star
14

java-classmate

Library for introspecting generic type information of types, member/static methods, fields. Especially useful for POJO/Bean introspection.
Java
258
star
15

jackson-jr

Stand-alone data-binding module designed as a light-weight (and -featured) alternative to `jackson-databind`: will only deal with "Maps, Lists, Strings, wrappers and Java Beans" (jr-objects), or simple read-only trees (jr-stree)
Java
239
star
16

woodstox

The gold standard Stax XML API implementation. Now at Github.
Java
226
star
17

jackson-dataformat-csv

(DEPRECATED) -- moved under: https://github.com/FasterXML/jackson-dataformats-text
Java
194
star
18

jackson-modules-base

Uber-project for foundational modules of Jackson that build directly on core components but nothing else; not including data format or datatype modules
Java
167
star
19

jackson-datatype-joda

Extension module to properly support full datatype set of Joda datetime library
Java
140
star
20

jackson-dataformat-yaml

Jackson module to add YAML backend (parser/generator adapters)
Java
138
star
21

jackson-jaxrs-providers

Multi-module project that contains Jackson-based "old" JAX-RS (ones under `javax.ws.rs`) providers for JSON, XML, YAML, Smile, CBOR formats
Java
111
star
22

smile-format-specification

New home for Smile format (https://en.wikipedia.org/wiki/Smile_(data_interchange_format))
92
star
23

jackson-datatype-jsr310

(DEPRECATED) -- moved under `jackson-modules-java8` repo: https://github.com/FasterXML/jackson-modules-java8
Java
92
star
24

jackson-module-afterburner

(DEPRECATED) -- moved under `jackson-modules-base`
Java
91
star
25

jackson-datatypes-collections

Jackson project that contains various collection-oriented datatype libraries: Eclipse Collections, Guava, HPPC, PCollections
Java
77
star
26

jackson-datatype-guava

(DEPRECATED) -- moved under `jackson-datatypes-collections`
Java
68
star
27

jackson-datatype-jdk8

(DEPRECATED) -- moved under `jackson-modules-java8`
Java
57
star
28

jackson-bom

Bill of materials POM for Jackson projects
Logos
54
star
29

jackson-datatype-json-org

(DEPRECATED) Support for org.json data types, to ease migration out of code that uses them
Java
49
star
30

jackson-dataformat-smile

(DEPRECATED) -- moved under `jackson-dataformats-binary
Java
44
star
31

jackson-module-jaxb-annotations

(DEPRECATED!!!) Moved to: https://github.com/FasterXML/jackson-modules-base/
Java
44
star
32

StaxMate

StaxMate: Automatic Shifting for Streaming XML Processing
Java
41
star
33

stax2-api

Extension API for Stax, Java pull-parsing API (STreaming Api for Xml)
Java
40
star
34

jackson-dataformat-cbor

(DEPRECATED) -- moved under `jackson-dataformats-binary`
Java
38
star
35

jackson-dataformat-avro

(DEPRECATED) -- moved under `jackson-dataformats-binary
Java
38
star
36

jackson-module-parameter-names

(DEPRECATED) -- moved under `jackson-modules-java8`
Java
33
star
37

jackson-dataformat-protobuf

(DEPRECATED) -- moved under `jackson-dataformats-binary`
Java
32
star
38

jackson-module-mrbean

(DEPRECATED) -- moved under `jackson-modules-base`
Java
27
star
39

jackson-datatypes-misc

Collection of common Jackson datatype modules not part of other multi-project repos
Java
22
star
40

TransiStore

Distributed data store for transient (temporary, time-bound) data. Based on ClusterMate/StoreMate
Java
21
star
41

jackson-datatype-jsr353

(DEPRECATED) -- moved under `jackson-datatypes-misc` https://github.com/FasterXML/jackson-datatypes-misc/
Java
19
star
42

jackson-future-ideas

Repository for SOLE PURPOSE of issue tracker and Wiki for NEW IDEAS. Please: NO BUG REPORTS.
18
star
43

jackson-benchmarks

Project that contains JMH-based micro-benchmarks to help with optimizations
Java
15
star
44

jackson-jakarta-rs-providers

Multi-module project that contains Jackson-based "new" Jakarta-RS (nee "JAX-RS" -- ones under `jakarta.ws.rs`) providers for JSON, XML, YAML, Smile, CBOR formats
Java
14
star
45

jackson-dataformat-properties

(DEPRECATED) -- moved under `jackson-dataformats-text`
Java
13
star
46

jackson-datatype-hppc

(DEPRECATED) -- moved under `jackson-datatypes-collections`
Java
9
star
47

oss-parent

Grandpa pom for all projects under FasterXML git umbrella
8
star
48

jackson-datatype-jdk7

(DEPRECATED) -- included in `jackson-databind` as of Jackson 2.7
Java
7
star
49

jvm-json-benchmark

Performance benchmark suite that compares data-binding (JSON<->POJO) performance of Java JSON libraries. Uses Japex benchmark framework for running tests and visualizing results.
Java
7
star
50

Hacktoberfest2020

Central repository for FasterXML activities related to Hacktoberfest 2020 by DigitalOcean (https://hacktoberfest.digitalocean.com/)
6
star
51

jackson-module-guice

(DEPRECATED) -- moved under `jackson-modules-base`
Java
5
star
52

jackson3-dev

Repository for planning and tracking development of Jackson 3.0, with bigger API changes
5
star
53

jackson-module-paranamer

(DEPRECATED) -- moved under `jackson-modules-base`
Java
5
star
54

jackson-parent

Parent pom for all core Jackson components (but only those -- users should use `jackson-bom`)
5
star
55

jackson-schema-maven-plugin

Maven plug-in for generation JSON Schemas using Jackson library and extension modules
Java
4
star
56

jackson-jdk11-compat-test

Test project for verifying Jackson's support of JDK9+ Module system
Java
3
star
57

jackson-dataformat-thrift

Not Yet A Thing -- placeholder for possible future implementation
Java
3
star
58

jackson-integration-tests

Project that contains integration tests across Jackson components
Java
3
star
59

jackson-jdk17-compat-test

Test suite for JDK 16 compatibility of Jackson components, mainly jackson-databind
Java
3
star
60

jackson-tools

Collection of command-line tools related to Jackson data processor, such as format decoders
Java
2
star
61

jackson-dataformat-ini

(Not Yet a Thing -- Placholder!) Data format implementation for "ini files", used on Windows, Python
Java
2
star
62

OmniPipe

Distributed data queue implementation that builds on ClusterMate/StoreMate foundation
2
star
63

jackson-jdk6-compat-test

Test project to verify JDK6 compatibility of Jackson versions 2.7 and anbove
Java
2
star
64

jackson-module-osgi

(DEPRECATED) -- moved under `jackson-modules-base`
Java
2
star
65

jackson-gh-actions

Repository for reusable Github workflow actions for Jackson project
2
star
66

Woodstox4

Backup repository for older versions of Woodstox (pre-5.0), migrated from Codehaus
Java
1
star