Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

FasterXML/jackson-module-kotlin

Repository files navigation

Maven CentralChange logTideliftKotlin Slack

Overview

Module that adds support for serialization/deserialization ofKotlinclasses 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

  • release2.19.0 (for Jackson2.19.x)GitHub Actions build
  • release2.18.3 (for Jackson2.18.x)GitHub Actions build
  • release2.17.3 (for Jackson2.17.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.19.+"

Maven:

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

Usage

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

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

// With Jackson 2.12 and laterimportcom.fasterxml.jackson.module.kotlin.jacksonObjectMapper...val mapper= jacksonObjectMapper()// orimportcom.fasterxml.jackson.module.kotlin.registerKotlinModule...val mapper=ObjectMapper().registerKotlinModule()// orimportcom.fasterxml.jackson.module.kotlin.jsonMapperimportcom.fasterxml.jackson.module.kotlin.kotlinModule...val mapper= jsonMapper {  addModule(kotlinModule())}

In 2.17 and later, thejacksonObjectMapper {} andregisterKotlinModule {} lambdas allow configuration forKotlinModule.
See#Configuration for details on the available configuration items.

A simple data class example:

importcom.fasterxml.jackson.module.kotlin.jacksonObjectMapperimportcom.fasterxml.jackson.module.kotlin.readValuedata classMyStateObject(valname:String,valage:Int)...val mapper= jacksonObjectMapper()val state= mapper.readValue<MyStateObject>(json)// orval state:MyStateObject= mapper.readValue(json)// ormyMemberWithType= mapper.readValue(json)

All inferred types for the extension functions carry in full generic information (reified generics).Therefore, usingreadValue() extension without theClass parameter will reify the type and automatically create aTypeReference for Jackson.

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

importcom.fasterxml.jackson.databind.node.ArrayNodeimportcom.fasterxml.jackson.databind.node.ObjectNodeimportcom.fasterxml.jackson.databind.node.JsonNodeFactoryimportcom.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+=truearrayNode+=1arrayNode+=1.0arrayNode+="bar".toByteArray()println(arrayNode.toString())// ["foo",true,1,1.0,"YmFy"]

Compatibility

Kotlin

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

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

  • Jackson 2.20.x: Kotlin-core 2.0 - 2.2
  • Jackson 2.19.x: Kotlin-core 1.9 - 2.1
  • Jackson 2.18.x: Kotlin-core 1.8 - 2.1
  • Jackson 2.17.x: Kotlin-core 1.7 - 2.0

Please note that the versions supported by 2.17 are tentative and may change depending on the release date.

Android

Supported Android SDK versions are determined byjackson-databind.Please seethis link for details.

Annotations

You can intermix non-field values in the constructor andJsonProperty 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)classStateObjectWithPartialFieldsInConstructor(valname:String, @JsonProperty("age")valyears:Int) {    @JsonProperty("address")lateinitvar primaryAddress:String// set after constructionvar createdDt:DateTime byDelegates.notNull()// set after constructionvar neverSetProperty:String?=null// not in JSON so must be nullable with default}

Note that usinglateinit orDelegates.notNull() will ensure that the value is nevernull 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 haveplatformStatic annotation, e.g.@JvmStatic). In these cases, annotate only one method asJsonCreator.
  • During deserialization, if the definition onKotlin is a non-null primitive andnull is entered explicitly onJSON, processing will continue with an unintended default value.This problem is fixed by enablingDeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES onObjectMapper.
  • Serializing a member or top-level Kotlin class that implements Iterator requires a workaround, seeIssue #4 for easy workarounds.
  • If using proguard:
    • kotlin.Metadata annotations may be stripped, preventing deserialization. Add a proguard rule to keep thekotlin.Metadata class:-keep class kotlin.Metadata { *; }
    • If you're gettingjava.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 packagecom.example.models, you could add the rule-keep class com.example.models.** { *; }
    • Also, please refer tothis page for settings related tojackson-databind.

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)

Deserialization forvalue class is also supported since 2.17.
Please refer tothis page for more information on usingvalue class, including serialization.

(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 knownat compile-time to Kotlin. This makescom.fasterxml.jackson.annotation.JsonSubTypes redundant.Acom.fasterxml.jackson.annotation.@JsonTypeInfo annotation at the base-class is still necessary.

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME)sealedclassSuperClass{classA:SuperClass()classB:SuperClass()}...val mapper= jacksonObjectMapper()val root:SuperClass= mapper.readValue(json)when(root){isA->"It's A"isB->"It's B"}

Configuration

The Kotlin module may be given a few configuration parameters at construction time;see theinline documentationfor 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 yourObjectMapper is constructed in Java, there is a builder methodprovided for configuring these options:

KotlinModulekotlinModule =newKotlinModule.Builder()        .enable(KotlinFeature.StrictNullChecks)        .build();ObjectMapperobjectMapper =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 allmaintenance work is strictly voluntary (no one gets paid to work on thisor any other Jackson components) so there is no guarantee for timeliness ofresponses.

All Pull Requests should be reviewed by at least one of active maintainers;bigger architectural/design questions should be agreed upon by majority ofactive maintainers.

Releases & Branches

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

Contributing

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

See themain Jackson contribution guidelines for more details.

Branches

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

  • 2.19 for bugfixes against the current stable version
  • 2.x for additive functionality & features orminor, backwards compatible changes to existing behavior to be included in the next minor version release
  • 3.x 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 thefailingpackage 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 theunderlying issue is fixed. This allows us to know when the tested functionality has been incidentally fixed byunrelated code changes.

See thetests readme for more information.


[8]ページ先頭

©2009-2025 Movatter.jp