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}")
相关推荐
Fate_I_C3 分钟前
Kotlin函数一
android·开发语言·kotlin
Eiceblue5 分钟前
C# 实现 XLS 与 XLSX 格式双向互转(无需依赖 Office)
开发语言·c#·visual studio
我讲个笑话你可别哭啊9 分钟前
Android Studio无线调试连接安卓设备
android·ide·android studio
pengyu10 分钟前
【Kotlin 协程修仙录 · 炼气境 · 初阶】 | 感受天地灵气,写出第一个挂起函数
android·kotlin
林栩link13 分钟前
Android CLI 与 Skills:提升 AI Coding 效率
android
水木流年追梦24 分钟前
CodeTop Top 300 热门题目2-最长回文子串
开发语言·人工智能·python·算法·leetcode
良木生香36 分钟前
【C++初阶】:STL——String从入门到应用完全指南(3)
c语言·开发语言·数据结构·c++·算法
fox_lht1 小时前
8.3.使用if let和let else实现简明的程序流控制
开发语言·后端·算法·rust
AI玫瑰助手1 小时前
Python基础:列表的定义、增删改查核心操作
android·开发语言·python
mOok ONSC1 小时前
对基因列表中批量的基因进行GO和KEGG注释
开发语言·数据库·golang