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}")
相关推荐
Mr_Xuhhh2 小时前
介绍一下ref
开发语言·c++·算法
nbsaas-boot2 小时前
软件开发最核心的理念:接口化与组件化
开发语言
lsx2024062 小时前
Java 对象概述
开发语言
Mr_Xuhhh2 小时前
C++11实现线程池
开发语言·c++·算法
无水先生2 小时前
python函数的参数管理(01)*args和**kwargs
开发语言·python
py小王子2 小时前
dy评论数据爬取实战:基于DrissionPage的自动化采集方案
大数据·开发语言·python·毕业设计
小陶的学习笔记3 小时前
python~基础
开发语言·python·学习
JMchen1233 小时前
Android UDP编程:实现高效实时通信的全面指南
android·经验分享·网络协议·udp·kotlin
lsx2024063 小时前
JavaScript 条件语句
开发语言
玄同7653 小时前
Python 自动发送邮件实战:用 QQ/163 邮箱发送大模型生成的内容
开发语言·人工智能·python·深度学习·机器学习·邮件·邮箱