Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a field optional in Kotlinx serialization

Here is my pojo class

@Serializable
data class Response(
    @SerialName("message") val message: String?,
    @SerialName("parameters") val parameters: Map<String, String>?
)

And this is Json, I was trying to decode from:

{
   "message": "Some text"
}

Here, the field parameters is optional. When I try to decode like

Json.decodeFromString<Response>(response)

I am getting the following exception:

kotlinx.serialization.MissingFieldException: Field 'parameters' is required for type with serial name 'Response', but it was missing

I was looking forward to set the field parameters to null, if the field is missing in the Json

like image 531
S Haque Avatar asked Dec 12 '25 11:12

S Haque


1 Answers

You need to specify a default value for your parameters property like this:

@Serializable
data class Response(
    @SerialName("message") val message: String?,
    @SerialName("parameters") val parameters: Map<String, String>? = null
)

You can read more about this here: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#optional-properties

like image 164
broot Avatar answered Dec 14 '25 23:12

broot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!