Kotlin 数据解析(Gson)

一、添加依赖

build.gradle.kts(:app)

复制代码
 // gson数据解析
 implementation("com.google.code.gson:gson:2.8.6")

对象类:

复制代码
// 对象类
class Account {
    var uid:String = "00001"
    var userName:String = "Freeman"
    var password:String = "admin"
    var telNumber:String = "13000000000"

    override fun toString(): String {
        return "Account(uid='$uid', userName='$userName', password='$password', telNumber='$telNumber')"
    }
}

JSON和对象互相转换:

复制代码
   // 测试所需json字符串
    val json = "{\"uid\":\"00001\",\"userName\":\"Freeman\",\"telNumber\":\"13000000000\"}"

    /**
     * JSON转换为对象
     * */
    val gson = Gson()
    val account = gson.fromJson<Account>(json,Account::class.java)
    println("json转换为对象:${account.toString()}")

    /**
     * 对象转换为JSON
     * */
    val accountJson:String = gson.toJson(account)
    println("对象转换为json:${accountJson}")

输出结果:

JSON和集合相互转换:

复制代码
 // 测试所需json字符串
    val json = "[{\"uid\":\"00001\",\"userName\":\"Freeman\",\"telNumber\":\"13000000000\"}," +
                "{\"uid\":\"00002\",\"userName\":\"man\",\"telNumber\":\"13000000001\"}]"

    /**
     * JSON转换为集合
     * */
    val gson = Gson()
    val accountList = gson.fromJson<List<Account>>(json,object:TypeToken<List<Account>>(){}.type)
    println("JSON转换为集合:${accountList}")
    println("集合数:${accountList.size}")

    /**
     * 集合转换为JSON
     * */
    val jsonList = gson.toJson(accountList)
    println("集合转换为JSON:${jsonList}")
相关推荐
kobe_OKOK_44 分钟前
Django `models.Field` 所有常见配置参数的完整清单与说明表
android
Paul_09201 小时前
golang面经——map模块和sync.Map模块
开发语言
Univin1 小时前
C++(10.5)
开发语言·c++·算法
haogexiaole2 小时前
Java高并发常见架构、处理方式、api调优
java·开发语言·架构
前行的小黑炭2 小时前
Android Compose :初步了解一下生命周期,对比原生android
android·kotlin·app
张人玉2 小时前
C# 通讯关键类的API
开发语言·c#
froginwe112 小时前
R 数组:深入解析与高效使用
开发语言
tao3556672 小时前
【Python刷力扣hot100】283. Move Zeroes
开发语言·python·leetcode
progalchemist3 小时前
Quick SwiftObjective-C测试框架入门教程
开发语言·其他·objective-c·swift