.encodeToString()
Anonymous contributor
Anonymous contributor2 total contributions
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 contributorAnonymous contributor2 total contributions
- Anonymous contributor
Looking to contribute?
- 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.