ZetCode

Kotlin JSON

最后修改于 2024 年 1 月 29 日

本文展示了如何在 Kotlin 中进行 JSON 序列化和反序列化。 我们使用 Gson 和 kotlinx.serialization 库。

JSON(JavaScript 对象表示法) 是一种轻量级的数据交换格式。它易于人类阅读和编写,也易于机器解析和生成。 与 XML 相比,它更简洁、更易读。 JSON 的官方互联网媒体类型是 application/json。 JSON 文件扩展名是 .json。 JSON 可以被 JavaScript 直接使用。

Gson 是一个 Java 序列化/反序列化库,用于将 Java 对象转换为 JSON 及其反向转换。 Gson 由 Google 创建,供内部使用,后来开源。

kotlinx.serialization 是一个用于序列化的 Kotlin 库。

Gson toJson

toJson 方法将指定对象序列化为其等效的 JSON 表示形式。

simple.kt
package com.zetcode

import com.google.gson.Gson

data class User(val firstName: String, val lastName: String)

fun main() {

    val colours = mutableMapOf(1 to "blue", 2 to "yellow", 3 to "green")

    val gson = Gson()
    val output = gson.toJson(colours)

    println(output)
}

在本例中,我们使用 toJSon 方法将一个 map 序列化为 JSON。

Gson fromJson

fromJson 方法将指定的 JSON 反序列化为指定类的对象。

simple2.kt
package com.zetcode

import com.google.gson.Gson

data class User(val firstName: String, val lastName: String)

fun main() {

    val jsonString = """{"firstName":"Tom", "lastName": "Broody"}"""

    val gson = Gson()
    val user: User = gson.fromJson(jsonString, User::class.java)

    println(user)
}

本例使用 fromJson 方法将 JSON 读入 Kotlin 对象。

GsonBuilder

GsonBuilder 使用各种配置设置构建 Gson。 GsonBuilder 遵循构建器模式,通常通过首先调用各种配置方法来设置所需的选项,最后调用 create 来使用它。

builder.kt
package com.zetcode

import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder

fun main() {

    val gson = GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .create()

    val user = User("Peter", "Flemming")

    println(gson.toJson(user))
}

在本例中,我们将一个对象写入 JSON。 我们使用 GsonBuilder 创建 Gson

val gson = GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
    .create()

我们使用 GsonBuilder 创建和配置 Gson。 字段命名策略设置为 FieldNamingPolicy.UPPER_CAMEL_CASE

美化打印 JSON 输出

Gson 有两种输出模式:紧凑模式和美化模式。

prettify.kt
package com.zetcode

import com.google.gson.GsonBuilder

fun main() {

    val gson = GsonBuilder().setPrettyPrinting().create()
    val items = mutableMapOf(1 to "pencil", 3 to "chair", 5 to "book")

    println(gson.toJson(items))
}

本例美化打印 JSON 输出。

val gson = GsonBuilder().setPrettyPrinting().create()

setPrettyPrinting 方法设置美化打印模式。

从 URL 读取 JSON

以下示例从网页读取 JSON 数据。 我们从 http://time.jsontest.com 获取 JSON 数据。

$ curl http://time.jsontest.com
{
    "date": "06-01-2022",
    "milliseconds_since_epoch": 1654109903352,
    "time": "06:58:23 PM"
}

GET 请求返回此 JSON 字符串。

read_page.kt
package com.zetcode

import com.google.gson.Gson
import java.net.URL

data class TimeData(val time:String, val milliseconds_since_epoch:Long, val date:String)

fun main() {

    val webPage = URL("http://time.jsontest.com")
    val data = webPage.readText()

    val gson = Gson()
    val td = gson.fromJson(data, TimeData::class.java)
    println(td)
}

代码示例从 http://time.jsontest.com 读取 JSON 数据。

在接下来的示例中,我们使用 kotlinx-serialization-json 库。

Json.encodeToString

Json.encodeToString 方法将给定的值序列化并编码为字符串。

plugins {
    kotlin("jvm") version "1.6.20"
    kotlin("plugin.serialization") version "1.6.21"
}
...
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.3")
    testImplementation(kotlin("test"))
}

我们需要设置库。

simple.kt
package com.zetcode

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class User(val name: String, val occupation: String)

fun main() {

    val u = User("John Doe", "gardener")
    val r = Json.encodeToString(u)

    println(r)
}

在本例中,我们序列化一个 User 类。

Json.decodeFromString

Json.decodeFromString 方法将给定的字符串解码并反序列化为给定类型的给定值。

simple2.kt
package com.zetcode

import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

@Serializable
data class User(val name: String, val occupation: String)

fun main() {

    val userJson = """{"name":"John Doe","occupation":"gardener"}"""
    val u = Json.decodeFromString<User>(userJson)

    println(u)
}

在本例中,我们将 JSON 字符串解码为 User 对象。

来源

Kotlin 序列化 - 文档

在本文中,我们展示了如何在 Kotlin 中使用 JSON。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 Kotlin 教程