How to get Jackson to use the default settings for Kotlin for missing values?

I have a Kotlin data class that looks like this:

data class SomeData( private val notInJson: String = "some default value", private val inJson: String ) 

and json string, I want to deserialize an instance of this class -

 { "inJson" : "value" } 

When I try to deserialize this data, I get an error that the notInJson parameter cannot be null. It seems that Jackson is passing him a null value, as he is missing from the json string.

Is there a way for Jackson to not pass any value for him so that you can use the default value specified in the class definition?

- EDIT -

I am registering KotlinModule () with mapper. Using version 2.7.8 or all jackson packages.

The following code is

 @Test fun jackson_kotlin_module() { val mapper = ObjectMapper().registerModule(KotlinModule()) println( mapper.readValue("""{ "inJson" : "some value" }""", SomeData::class.java)) } 

gives me -

 com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class SomeData] value failed (java.lang.IllegalArgumentException): Parameter specified as non-null is null: method SomeData.<init>, parameter notInJson at [Source: { "inJson" : "some value" }; line: 1, column: 27] 
+6
source share
1 answer

The default parameter is the Kotlin function. Jackson does not know about this, so we need to somehow communicate this in order to support him. Fortunately, there is a great jackson-kotlin-module that allows you to:

 val mapper: ObjectMapper = ObjectMapper() .registerModule(KotlinModule()) //let Jackson know about Kotlin ... data class SomeData( private val notInJson: String = "some default value", private val inJson: String ) ... val data = mapper.readValue<SomeData>("""{"inJson": "sample value"}""") println(data) // -> SomeData(notInJson=some default value, inJson=sample value) 

For usage instructions, see the jackson-kotlin-module Readme and pay particular attention to the versions of the module and Jackson himself. In order for the default parameters to work, you need at least version 2.8.4 jackson-kotlin-module

+7
source

Source: https://habr.com/ru/post/1011794/


All Articles