Kotlin serialization是由kotlin官方提供,可将kotlin对象序列化和反序列化的插件,支持序列化格式包括:JSON, Protobuf, CBOR, Hocon 和Properties
serialization使用非常简单:
//序列化
val data = Project("kotlinx.serialization", "Kotlin")
val json = Json.encodeToString(data)
//反序列化
val obj = Json.decodeFromString<Project>(json)
一、添加serialization依赖
在module build.gradle里添加
plugins {
id 'kotlin-android'
id 'kotlinx-serialization'
id 'kotlin-kapt'
}
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
}
在project build.gradle里添加
buildscript {
ext.kotlin_version = '1.5.31'
repositories { mavenCentral() }
dependencies {
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}
}
二、Kotlin 序列化指南
1、序列化操作
@Serializable
class Project(val name: String, val language: String)
fun main() {
val data = Project("kotlinx.serialization", "Kotlin")
println(Json.encodeToString(data))
}
1、可以被序列化的字段
只有具有支持字段的类的属性会被序列化,因此具有 getter/setter 且没有支持字段和委托属性的属性不会被序列化,如下例所示。
@Serializable
class Project(
// name带有支持字段属性,可以被序列化
var name: String
) {
var stars: Int = 0 // 带有支持字段属性,可以被序列化
val path: String //未带字段,不会被序列化
get() = "kotlin/$name"
var id by ::name //代理属性,不会被序列化
}
fun main() {
val data = Project("kotlinx.serialization").apply { stars = 9000 }
println(Json.encodeToString(data))
}
//print:{"name":"kotlinx.serialization","stars":9000}
2、默认值操作
默认情况下,默认值不会参与编码:
@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"}
如果需要默认值参与序列化,可设置encodeDefaults属性:
@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}
如果不希望null参与序列化,explicitNulls可设置为false
3、强制安全类型
serialization执行Kotlin语言的类型安全,如果json里面有null,而对应属性没有标记为可空,则会报异常
@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)
}
报错: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.
如果希望json为null时,使用默认值,则设置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、序列字段名称
默认情况下,编码表示中使用的属性名称(在我们的示例中为 JSON)与它们在源代码中的名称相同。用于序列化的名称称为序列名称,可以使用@SerialName注释进行更改
@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、反序列化操作
@Serializable
class Project(val name: String, val language: String)
fun main() {
val data = Project("kotlinx.serialization", "Kotlin")
println(Json.encodeToString(data))
}
1、可选属性
只有在序列中存在对象的所有属性时,才能反序列化对象。例如:
@Serializable
data class Project(val name: String, val language: String)
fun main() {
val data = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""")
println(data)
}
由于json中没有language属性,会报异常:Exception in thread "main" kotlinx.serialization.MissingFieldException: Field 'language' is required for type with serial name 'example.exampleClasses04.Project', but it was missing
可以通过向属性添加默认值来修复此问题,如:
@Serializable
data class Project(val name: String, val language: String = "Kotlin")
fun main() {
val data = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""")
println(data)
}
打印结果:Project(name=kotlinx.serialization, language=Kotlin)
2、必需属性
在反序列化,如果你希望json必需包含指定的属性名,可以使用@Required注解
@Serializable
data class Project(val name: String, @Required val language: String = "Kotlin")
fun main() {
val data = Json.decodeFromString<Project>("""
{"name":"kotlinx.serialization"}
""")
println(data)
}
例子中,由于json未包含被标记为@Required的language属性,会报异常Field 'language' is required for type with serial name 'example.exampleClasses07.Project', but it was missing
3、JSON属性设置
Json {
prettyPrint = true //json格式化
isLenient = true //宽松解析,json格式异常也可解析,如:{name:"小红",age:"18"}
ignoreUnknownKeys = true //忽略未知键,如{"name":"小红","age":"18"} ->Person(val name:String)
coerceInputValues = true //强制输入值,如果json属性与对象格式不符,则使用对象默认值,如:{"name":"小红","age":null} + Person(val name:String = "小绿",val age:Int = 18) ->Person("小红",18)
encodeDefaults = true //编码默认值,默认情况下,默认值的属性不会参与序列化,通过设置encodeDefaults = true,可让默认属性参与序列化(可参考上述例子)
explicitNulls = true //序列化时是否忽略null
allowStructuredMapKeys = true //允许结构化映射(map的key可以使用对象)
allowSpecialFloatingPointValues = true //特殊浮点值:允许Double为NaN或无穷大
}