Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring null fields when deserializing with Jackson

Tags:

kotlin

jackson

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?

like image 506
George Avatar asked Nov 08 '22 10:11

George


1 Answers

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)

like image 171
kurt Avatar answered Dec 16 '22 06:12

kurt