Reputation: 507
I have the following Kotlin data class:
data class TestObject(
val boolField: Boolean,
val stringField: String,
val nullBoolField: Boolean = true,
val nullStringField: String = "default",
val notThereBoolField: Boolean = true,
val notThereStringField: String = "not there"
)
I am then attempting to deserialize some JSON into this class using Jackson v2.9.4 with the Jackson Kotlin plugin v2.9.4.1. The test JSON is as follows:
{
"boolField": true,
"stringField": "string",
"nullBoolField": null,
"nullStringField": null
}
The first two and the last two fields deserialize successfully - with the values from the JSON and the default values from the Kotlin data class, as appropriate. However, when the middle pair of fields are present, the deserialization fails with:
Instantiation of [simple type, class com.example.TestObject] value failed for JSON property nullStringField due to missing (therefore NULL) value for creator parameter nullStringField which is a non-nullable type
I know I could solve the problem by changing the types of nullBoolField
and nullStringField
to Boolean?
and String?
respectively, but since default values are known I would rather not have to push the handling of null
further down into the code by doing that.
The question is: is there any way of configuring Jackson to use the Kotlin data class default values for non-nullable properties when the property is present in the JSON but set to null?
Upvotes: 7
Views: 4043
Reputation: 434
If you're mapping to Java 8, you can use:
val kotlinModule = KotlinModule.Builder()
.disable(KotlinFeature.StrictNullChecks)
.build()
val objectMapper = ObjectMapper()
objectMapper.registerModules(
Jdk8Module(),
kotlinModule
)
Upvotes: 0
Reputation: 1550
You could try first to filter null values from json
and after to deserialize it to Kotlin object.
Or you may to try add feature to kotlin-jackson
module, with adding a new feature parameter, which will enable a null ignoring from json parameters and use default values.
You may do this by modify this line (if I'm not mistaken)
Upvotes: 1
Reputation: 6381
If you don't have any value and field is non-nullable then you should not pass it in request body:
{
"boolField": true,
"stringField": "string"
}
This results in following object, as expected:
{
"boolField": true,
"stringField": "string",
"nullBoolField": true,
"nullStringField": "default",
"notThereBoolField": true,
"notThereStringField": "not there"
}
Upvotes: 0