2

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.

barryalan2633
  • 610
  • 7
  • 21

1 Answers1

3

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

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

Iyxan23
  • 106
  • 2
  • 8
  • https://stackoverflow.com/questions/62254149/kotlinx-serialization-how-to-parse-to-different-varaiable-name-than-the-exact I was wrongly using the annotation for GSON, thanks – barryalan2633 Dec 10 '21 at 01:06