当前位置:   article > 正文

kotlin serialization 使用指南(一)

kotlin serialization

Kotlin serialization是由kotlin官方提供,可将kotlin对象序列化和反序列化的插件,支持序列化格式包括:JSON, Protobuf, CBOR, Hocon 和Properties 

serialization使用非常简单:

  1. //序列化
  2. val data = Project("kotlinx.serialization", "Kotlin")
  3. val json = Json.encodeToString(data)
  4. //反序列化
  5. val obj = Json.decodeFromString<Project>(json)

一、添加serialization依赖

在module build.gradle里添加

  1. plugins {
  2. id 'kotlin-android'
  3. id 'kotlinx-serialization'
  4. id 'kotlin-kapt'
  5. }
  6. dependencies {
  7. implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
  8. }

在project build.gradle里添加

  1. buildscript {
  2. ext.kotlin_version = '1.5.31'
  3. repositories { mavenCentral() }
  4. dependencies {
  5. classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
  6. }
  7. }

二、Kotlin 序列化指南

1、序列化操作        

  1. @Serializable
  2. class Project(val name: String, val language: String)
  3. fun main() {
  4. val data = Project("kotlinx.serialization", "Kotlin")
  5. println(Json.encodeToString(data))
  6. }

   1、可以被序列化的字段

         只有具有支持字段的类的属性会被序列化,因此具有 getter/setter 且没有支持字段和委托属性的属性不会被序列化,如下例所示。

  1. @Serializable
  2. class Project(
  3. // name带有支持字段属性,可以被序列化
  4. var name: String
  5. ) {
  6. var stars: Int = 0 // 带有支持字段属性,可以被序列化
  7. val path: String //未带字段,不会被序列化
  8. get() = "kotlin/$name"
  9. var id by ::name //代理属性,不会被序列化
  10. }
  11. fun main() {
  12. val data = Project("kotlinx.serialization").apply { stars = 9000 }
  13. println(Json.encodeToString(data))
  14. }
  15. //print:{"name":"kotlinx.serialization","stars":9000}

    2、默认值操作

       默认情况下,默认值不会参与编码:       

  1. @Serializable
  2. data class Project(val name: String, val language: String = "Kotlin")
  3. fun main() {
  4. val data = Project("kotlinx.serialization")
  5. println(Json.encodeToString(data))
  6. }
  7. //print:{"name":"kotlinx.serialization"}

        如果需要默认值参与序列化,可设置encodeDefaults属性:

  1. @Serializable
  2. class Project(
  3. val name: String, val language: String = "Kotlin", val website: String? = null)
  4. fun main() {
  5. val data = Project("kotlinx.serialization")
  6. println(Json { encodeDefaults = true }.encodeToString(data))
  7. }
  8. //print:{"name":"kotlinx.serialization","language":"Kotlin","website":null}

       如果不希望null参与序列化,explicitNulls可设置为false

3、强制安全类型

serialization执行Kotlin语言的类型安全,如果json里面有null,而对应属性没有标记为可空,则会报异常

  1. @Serializable
  2. data class Project(val name: String, val language: String = "Kotlin")
  3. fun main() {
  4. val data = Json.decodeFromString<Project>("""
  5. {"name":"kotlinx.serialization","language":null}""")
  6. println(data)
  7. }

报错: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

  1. @Serializable
  2. data class Project(val name: String, val language: String = "Kotlin")
  3. fun main() {
  4. val data = Json { coerceInputValues = true }.decodeFromString<Project>("""
  5. {"name":"kotlinx.serialization","language":null}
  6. """)
  7. println(data)
  8. }
  9. //print:Project(name=kotlinx.serialization, language=Kotlin)

4、序列字段名称

默认情况下,编码表示中使用的属性名称(在我们的示例中为 JSON)与它们在源代码中的名称相同。用于序列化的名称称为序列名称,可以使用@SerialName注释进行更改
 

  1. @Serializable
  2. class Project(val name: String, @SerialName("lang") val language: String)
  3. fun main() {
  4. val data = Project("kotlinx.serialization", "Kotlin")
  5. println(Json.encodeToString(data))
  6. }
  7. //print:{"name":"kotlinx.serialization","lang":"Kotlin"}

2、反序列化操作

  1. @Serializable
  2. class Project(val name: String, val language: String)
  3. fun main() {
  4. val data = Project("kotlinx.serialization", "Kotlin")
  5. println(Json.encodeToString(data))
  6. }

1、可选属性

只有在序列中存在对象的所有属性时,才能反序列化对象。例如:

  1. @Serializable
  2. data class Project(val name: String, val language: String)
  3. fun main() {
  4. val data = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""")
  5. println(data)
  6. }

由于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

可以通过向属性添加默认值来修复此问题,如:

  1. @Serializable
  2. data class Project(val name: String, val language: String = "Kotlin")
  3. fun main() {
  4. val data = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""")
  5. println(data)
  6. }
  7. //print:Project(name=kotlinx.serialization, language=Kotlin)

2、必需属性

在反序列化,如果你希望json必需包含指定的属性名,可以使用@Required注解

  1. @Serializable
  2. data class Project(val name: String, @Required val language: String = "Kotlin")
  3. fun main() {
  4. val data = Json.decodeFromString<Project>("""
  5. {"name":"kotlinx.serialization"}
  6. """)
  7. println(data)
  8. }

例子中,由于json未包含被标记为@Required的language属性,会报异常Field 'language' is required for type with serial name 'example.exampleClasses07.Project', but it was missing

 3、JSON属性设置

  1. Json {
  2. prettyPrint = true //json格式化
  3. isLenient = true //宽松解析,json格式异常也可解析,如:{name:"小红",age:"18"} + Person(val name:String,val age:Int) ->Person("小红",18)
  4. ignoreUnknownKeys = true //忽略未知键,如{"name":"小红","age":"18"} ->Person(val name:String)
  5. coerceInputValues = true //强制输入值,如果json属性与对象格式不符,则使用对象默认值,如:{"name":"小红","age":null} + Person(val name:String = "小绿",val age:Int = 18) ->Person("小红",18)
  6. encodeDefaults = true //编码默认值,默认情况下,默认值的属性不会参与序列化,通过设置encodeDefaults = true,可让默认属性参与序列化(可参考上述例子)
  7. explicitNulls = true //序列化时是否忽略null
  8. allowStructuredMapKeys = true //允许结构化映射(map的key可以使用对象)
  9. allowSpecialFloatingPointValues = true //特殊浮点值:允许Double为NaN或无穷大
  10. }

1、格式化 

  1. @Serializable
  2. data class Person(val name:String,val age:Int)
  3. val json = Json {
  4. prettyPrint = true //是否格式化,默认false
  5. prettyPrintIndent = " " //除首行外各行缩进,默认四个空格
  6. }
  7. println(json.encodeToString(Person("小明",18)))
  8. //print:
  9. {
  10. "name": "小明",
  11. "age": 18
  12. }

2、宽松解析

  1. val json = "{name:小明,age:\"18\"}" //这是一条格式有问题的json
  2. val person = Json {
  3. isLenient = true //json格式有问题,也有可能解析成功,默认false
  4. }.decodeFromString<Person>(json)
  5. println(person)
  6. //print:Person(name=小明, age=18)

 3、忽略未知键

默认情况下,json和实例化对像键值需要一一对应,但实际案例中,json和对象参数名可能无法一一对应,这种情况可以忽略未使用的键

  1. @Serializable
  2. data class Person(val name:String)
  3. val json = """{"name":"小明","age":18}"""
  4. println(Json{
  5. ignoreUnknownKeys = true
  6. }.decodeFromString<Person>(json))
  7. //print:Person(name=小明)

4、强制输入值

json的值类型和实例化对象类型不一致时,使用对象的默认值

  1. @Serializable
  2. data class Person(val name:String = "小明",val age:Int = 18)
  3. val json = """{"name":"小红","age":null}"""
  4. println(Json{
  5. coerceInputValues = true //默认false
  6. }.decodeFromString<Person>(json))
  7. //print:Person(name=小红, age=18)

5、编码默认值

序列化时,对象默认值参与序列化

  1. @Serializable
  2. data class Person(val name:String = "小明",val age:Int = 18)
  3. println(Json{
  4. encodeDefaults = false
  5. }.encodeToString(Person(name = "小红")))
  6. //plint:{"name":"小红"}
  7. println(Json{
  8. encodeDefaults = true
  9. }.encodeToString(Person(name = "小红")))
  10. //plint:{"name":"小红","age":18}

6、序列化时忽略null

  1. @Serializable
  2. data class Person(val name:String = "小明",val age:Int? = null)
  3. println(Json{
  4. encodeDefaults = true
  5. explicitNulls = false
  6. }.encodeToString(Person(name = "小红",age = null)))
  7. //print:{"name":"小红"}
  8. //explicitNulls = true时,值为null也会参与序列化
  9. println(Json{
  10. encodeDefaults = true
  11. explicitNulls = true
  12. }.encodeToString(Person(name = "小红",age = null)))
  13. //print:{"name":"小红","age":null}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/259846
推荐阅读
相关标签
  

闽ICP备14008679号