Search code examples
androidkotlinktorjson-serializationktor-client

Using @SerializedName with hyphen not working


I am trying to deserialize this JSON response into an object and one of my keys has a hyphen on it. Unfortunately, Kotlin does not support hyphens in variable names which is why I used @SerializedName() but it is still now working. Any clues as to why?

JSON Response

[
    {
        "dateCreated": "07-22-2021",
        "comments": "Comment",
        "vehicle_type": "Sedan",
        "name": "Leagacy Nissan Template",
        "template-type": "", //this is giving me the problem
        "template_uses_type": "Both"
        ...
    }
]

My object:

@Serializable
data class SpinDataResponse(
    val dateCreated:String,
    val comments: String,
    val vehicle_type:String,
    val name:String,
    @SerializedName("template-type") val template_type:String,
    val template_uses_type:String,
    ...
)

Error:

I/System.out: Error: Unexpected JSON token at offset 120: Encountered an unknown key 'template-type'. Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys. JSON input: ....."name": "Nissan PathFinder", "template-type": "", "template_.....

I don't want to ignore the unknown key because I actually need it.


Solution

  • Shouldn't it be @SerialName("")?

    https://kotlin.github.io/kotlinx.serialization/kotlinx-serialization-core/kotlinx-serialization-core/kotlinx.serialization/-serial-name/index.html