Kotlin .encodeToString()
Anonymous contributor
Published Nov 21, 2023
Contribute to Docs
The encodeToString() function is provided by the Kotlin Serialization library. It is used for serializing data to a string representation (commonly in JSON format).
Syntax
fun <T> encodeToString(serializer: SerializationStrategy<T>, value: T): String
serializer:An instance of SerializationStrategy that defines how the data should be serialized.value:The object or data to be serialized to a string.
Example
Here is an example of how to use encodeToString() to serialize data into a JSON string:
import kotlinx.serialization.Serializableimport kotlinx.serialization.encodeToStringimport kotlinx.serialization.json.Json@Serializabledata class Person(val name: String, val age: Int)fun main() {val person = Person("Johnny", 30)// Serialize the data class to a JSON string using encodeToString()val jsonString = Json.encodeToString(person)println(jsonString)}
This will print the following output:
{"name": "Johnny","age": 30}
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
- Beginner Friendly.9 hours