kotlinx.serialization : How to parse to different varaiable name than the exact name of JSON key
Asked Answered
B

2

29

With GSON we used @SerializedName to parse JSON object which didn't have the same key to that of the variable name in Kotlin.

data class User (
    @SerializedName("id")
    long userId;
    @SerializedName("fullName")
    String name;
)

In kotlinx.serialization we can serialize an object like this but how to give different JSON key to a varaible during (de)serialization?

@Serializable
data class User (
    long userId;
    String name;
)
Basir answered 8/6, 2020 at 2:33 Comment(0)
B
65

Use @SerialName like we used @SerializedName in GSON

GSON

data class User (
    @SerializedName("id")
    long userId;
    @SerializedName("fullName")
    String name;
)

kotlinx.serialization

@Serializable
data class User (
    @SerialName("id")
    long userId;
    @SerialName("fullName")
    String name;
)
Basir answered 8/6, 2020 at 2:33 Comment(3)
so it's a bit complicated now by one line where we have to add annotation @Serializable for each network entities :)Pasquinade
Just to add a link to the documentation: github.com/Kotlin/kotlinx.serialization/blob/master/docs/…Frenchify
Thanks for the answer. Saves me from trouble.Rancorous
A
5

According to the documentation :

The names of the properties used in encoded representation, JSON in our examples, are the same as their names in the source code by default. The name that is used for serialization is called a serial name, and can be changed using the @SerialName annotation. For example, we can have a language property in the source with an abbreviated serial name.

@Serializable
class Project(val name: String, @SerialName("lang") val language: String)

fun main() {
    val data = Project("kotlinx.serialization", "Kotlin")
    println(Json.encodeToString(data))
}
Apparent answered 16/10, 2021 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.