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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With