implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
@Serializable
data class User(
val id: Int,
val name: String,
val email: String
)
import kotlinx.serialization.json.Json
val json = """
{
"id": 1,
"name": "John Doe",
"email": "johndoe@example.com"
}
""".trimIndent()
val user = Json.decodeFromString<User>(json)
println(user.id) // 1
println(user.name) // "John Doe"
println(user.email) // "johndoe@example.com"
You can also serialize your data classes into json strings:
val serializedString = Json.encodeToString(user)
println(serializedString) // {"id":1,"name":"John Doe","email":"johndoe@example.com"}
Note: Be sure to import kotlinx.serialization.json.Json at the top of your file.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-12-21 11:00:00 +0000
Seen: 9 times
Last updated: Sep 07 '22
Why can't IntelliJ IDEA detect the Kotlin multiplatform library?
How to implement map function on Kotlin's Stateflow?
What is the correlation between coroutines and the Kotlin Gradle Plugin?
When the library throws a JsonDataException, why does the Kotlin Moshi adapter return null?
What are the typical approaches found in a Gradle build script?
Which languages are appropriate to use for a contemporary website?