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)
}
//print: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"} + Person(val name:String,val age:Int) ->Person("小红",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或无穷大
}
1、格式化
@Serializable
data class Person(val name:String,val age:Int)
val json = Json {
prettyPrint = true //是否格式化,默认false
prettyPrintIndent = " " //除首行外各行缩进,默认四个空格
}
println(json.encodeToString(Person("小明",18)))
//print:
{
"name": "小明",
"age": 18
}
2、宽松解析
val json = "{name:小明,age:\"18\"}" //这是一条格式有问题的json
val person = Json {
isLenient = true //json格式有问题,也有可能解析成功,默认false
}.decodeFromString<Person>(json)
println(person)
//print:Person(name=小明, age=18)
3、忽略未知键
默认情况下,json和实例化对像键值需要一一对应,但实际案例中,json和对象参数名可能无法一一对应,这种情况可以忽略未使用的键
@Serializable
data class Person(val name:String)
val json = """{"name":"小明","age":18}"""
println(Json{
ignoreUnknownKeys = true
}.decodeFromString<Person>(json))
//print:Person(name=小明)
4、强制输入值
json的值类型和实例化对象类型不一致时,使用对象的默认值
@Serializable
data class Person(val name:String = "小明",val age:Int = 18)
val json = """{"name":"小红","age":null}"""
println(Json{
coerceInputValues = true //默认false
}.decodeFromString<Person>(json))
//print:Person(name=小红, age=18)
5、编码默认值
序列化时,对象默认值参与序列化
@Serializable
data class Person(val name:String = "小明",val age:Int = 18)
println(Json{
encodeDefaults = false
}.encodeToString(Person(name = "小红")))
//plint:{"name":"小红"}
println(Json{
encodeDefaults = true
}.encodeToString(Person(name = "小红")))
//plint:{"name":"小红","age":18}
6、序列化时忽略null
@Serializable
data class Person(val name:String = "小明",val age:Int? = null)
println(Json{
encodeDefaults = true
explicitNulls = false
}.encodeToString(Person(name = "小红",age = null)))
//print:{"name":"小红"}
//explicitNulls = true时,值为null也会参与序列化
println(Json{
encodeDefaults = true
explicitNulls = true
}.encodeToString(Person(name = "小红",age = null)))
//print:{"name":"小红","age":null}