6

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

S Haque
  • 6,881
  • 5
  • 29
  • 35

1 Answers1

13

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

broot
  • 21,588
  • 3
  • 30
  • 35