Ask Your Question
0

How to use Kotlinx serialization for parsing json?

asked 2022-12-21 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-09-07 03:00:00 +0000

lakamha gravatar image
  1. Add kotlinx-serialization-json dependency to your project:
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
  1. Define your data classes and annotate them with @Serializable
@Serializable
data class User(
    val id: Int,
    val name: String,
    val email: String
)
  1. Use the Json object to parse the json string into an instance of your data class
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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-12-21 11:00:00 +0000

Seen: 9 times

Last updated: Sep 07 '22