简体   繁体   English

在 Kotlinx 序列化中将字段设为可选

[英]Make a field optional in Kotlinx serialization

Here is my pojo class这是我的 pojo 课

@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:这是 Json,我试图从以下内容解码:

{
   "message": "Some text"
}

Here, the field parameters is optional.此处,字段parameters是可选的。 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 kotlinx.serialization.MissingFieldException:序列名称为“Response”的类型需要字段“parameters”,但缺少字段

I was looking forward to set the field parameters to null , if the field is missing in the Json我期待将字段parameters设置为null ,如果该字段在Json丢失

You need to specify a default value for your parameters property like this:您需要为parameters属性指定一个默认值,如下所示:

@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您可以在此处阅读更多相关信息: https : //github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#optional-properties

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM