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}")
相关推荐
wangjialelele几秒前
二刷C语言后,一万字整理细碎知识点
c语言·开发语言·数据结构·c++·算法·cpp
mjhcsp4 分钟前
P3145 [USACO16OPEN] Splitting the Field G(题解)
开发语言·c++·算法
rit84324997 分钟前
UVE算法提取光谱特征波长的MATLAB实现与应用
开发语言·算法·matlab
阿蒙Amon12 分钟前
C#每日面试题-简述反射
开发语言·面试·c#
独行soc13 分钟前
2026年渗透测试面试题总结-5(题目+回答)
android·网络·python·安全·web安全·渗透测试
越甲八千17 分钟前
python socket
开发语言·python
缺点内向19 分钟前
告别“复制粘贴”:用C#和模板高效生成Word文档
开发语言·c#·word
edisao20 分钟前
【开源】轻量级 LLM 文本质检工具:精准识别核心概念缺失,支持动态别名 + 反馈闭环
大数据·开发语言·人工智能·经验分享·gpt·架构·开源
Leweslyh29 分钟前
【实战】如何在家定位国际空间站 (ISS)? —— 坐标转换的魔法 (例题 5.9)
开发语言·javascript·ecmascript
Sheep Shaun30 分钟前
深入理解AVL树:从概念到完整C++实现详解
服务器·开发语言·数据结构·c++·后端·算法