Kotlin .decodeFromString()
Anonymous contributor
Published Dec 7, 2023
Contribute to Docs
The .decodeFromString() function is provided by the Kotlin Serialization library, used for deserializing data from a string representation (in JSON format) into a Kotlin object.
Syntax
fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T
deserializer:An instance of DeserializationStrategy that defines how the string should be deserialized into data.string:The string representation (e.g. JSON) of the data to be deserialized.
Example
Here is an example of how to use .decodeFromString() to deserialize data from a JSON string into a Kotlin object:
import kotlinx.serialization.*import kotlinx.serialization.json.Json@Serializabledata class Person(val name: String, val age: Int)fun main() {val jsonString = """{"name": "Johnny","age": 30}"""// Deserialize the JSON string into a Person object using decodeFromString()val person = Json.decodeFromString<Person>(jsonString)println(person)}
The above example will result in the following output:
Person(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