Kotlin serialization is a plug-in officially provided by kotlin, which can serialize and deserialize kotlin objects. The supported serialization formats include JSON, Protobuf, CBOR, Hocon and Properties
serialization is easy to use:
//serialize val data = Project("kotlinx.serialization", "Kotlin") val json = Json.encodeToString(data) //Deserialization val obj = Json.decodeFromString<Project>(json)
1, Add serialization dependency
In module Add in build.gradle
plugins { id 'kotlin-android' id 'kotlinx-serialization' id 'kotlin-kapt' } dependencies { implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0" }
In project Add in build.gradle
buildscript { ext.kotlin_version = '1.5.31' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" } }
2, Kotlin serialization Guide
1. Serialization operation
@Serializable class Project(val name: String, val language: String) fun main() { val data = Project("kotlinx.serialization", "Kotlin") println(Json.encodeToString(data)) }
1. Fields that can be serialized
Only properties of classes with supported fields will be serialized, so properties with getters / setters and without supported fields and delegate properties will not be serialized, as shown in the following example.
@Serializable class Project( // name has supported field properties and can be serialized var name: String ) { var stars: Int = 0 // With supported field properties, it can be serialized val path: String //Without field, it will not be serialized get() = "kotlin/$name" var id by ::name //Proxy properties, not serialized } fun main() { val data = Project("kotlinx.serialization").apply { stars = 9000 } println(Json.encodeToString(data)) } //print:{"name":"kotlinx.serialization","stars":9000}
2. Default action
By default, the default value does not participate in encoding:
@Serializable data class Project(val name: String, val language: String = "Kotlin") fun main() { val data = Project("kotlinx.serialization") println(Json.encodeToString(data)) } print:{"name":"kotlinx.serialization"}
If you need the default value to participate in serialization, you can set the encodeDefaults property:
@Serializable class Project( val name: String, val language: String = "Kotlin", val website: String? = null) fun main() { val data = Project("kotlinx.serialization") println(Json { encodeDefaults = true }.encodeToString(data)) } print:{"name":"kotlinx.serialization","language":"Kotlin","website":null}
Explicit nulls can be set to false if you do not want null to participate in serialization
3. Mandatory security type
serialization implements the type safety of Kotlin language. If there is null in json and the corresponding attribute is not marked as nullable, an exception will be reported
@Serializable data class Project(val name: String, val language: String = "Kotlin") fun main() { val data = Json.decodeFromString<Project>(""" {"name":"kotlinx.serialization","language":null}""") println(data) }
Error: Unexpected JSON token at offset 52: Expected string literal but 'null' literal was found
Use 'coerceInputValues = true' in 'Json {}` builder to coerce nulls to default values.
If you want to use the default value when json is null, set coerceInputValues = true
@Serializable data class Project(val name: String, val language: String = "Kotlin") fun main() { val data = Json { coerceInputValues = true }.decodeFromString<Project>(""" {"name":"kotlinx.serialization","language":null} """) println(data) } print: Project(name=kotlinx.serialization, language=Kotlin)
4. Sequence field name
By default, the attribute names used in the encoded representation (JSON in our example) are the same as their names in the source code. The name used for serialization is called the sequence name and can be changed using the @ SerialName annotation
@Serializable class Project(val name: String, @SerialName("lang") val language: String) fun main() { val data = Project("kotlinx.serialization", "Kotlin") println(Json.encodeToString(data)) } print: {"name":"kotlinx.serialization","lang":"Kotlin"}
2. Deserialization operation
@Serializable class Project(val name: String, val language: String) fun main() { val data = Project("kotlinx.serialization", "Kotlin") println(Json.encodeToString(data)) }
1. Optional properties
An object can be deserialized only if all the properties of the object exist in the sequence. For example:
@Serializable data class Project(val name: String, val language: String) fun main() { val data = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""") println(data) }
Because there is no language attribute in json, an exception will be reported: Exception in thread "main" kotlinx.serialization.MissingFieldException: Field 'language' is required for type with serial name 'example.exampleClasses04.Project', but it was missing
You can fix this problem by adding default values to properties, such as:
@Serializable data class Project(val name: String, val language: String = "Kotlin") fun main() { val data = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""") println(data) } Print results: Project(name=kotlinx.serialization, language=Kotlin)
2. Required properties
In deserialization, if you want json to contain the specified attribute name, you can use the @ Required annotation
@Serializable data class Project(val name: String, @Required val language: String = "Kotlin") fun main() { val data = Json.decodeFromString<Project>(""" {"name":"kotlinx.serialization"} """) println(data) }
In the example, because json does not contain the language attribute marked @ Required, an exception will be reported. Field 'language' is Required for type with serial name 'example. Exampleclasss07. Project', but it was missing
3. JSON property settings
Json { prettyPrint = true //json formatting isLenient = true //Loose parsing, json format exceptions can also be parsed, such as: {name: "Xiaohong", age:"18"} ignoreUnknownKeys = true //Ignore unknown keys, such as {"name": "little red", "age": "18"} - > person (Val Name: String) coerceInputValues = true //Forced input value. If the json attribute does not match the object format, the object default value is used, such as: {name ":" little red "," age":null} + Person(val name:String =" little green ", Val age: int = 18) - > person (" little red ", 18) encodeDefaults = true //Encode the default value. By default, the attribute of the default value will not participate in serialization. By setting encodeDefaults = true, the default attribute can participate in serialization (refer to the above example) explicitNulls = true //Ignore null when serializing allowStructuredMapKeys = true //Allow structured mapping (map key s can use objects) allowSpecialFloatingPointValues = true //Special floating point value: Double is allowed to be NaN or infinity }