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}")
相关推荐
妮妮喔妮3 分钟前
【无标题】
开发语言·前端·javascript
fie88898 分钟前
浅谈几种js设计模式
开发语言·javascript·设计模式
喝可乐的布偶猫15 分钟前
Java类变量(静态变量)
java·开发语言·jvm
喝可乐的布偶猫1 小时前
韩顺平之第九章综合练习-----------房屋出租管理系统
java·开发语言·ide·eclipse
江山如画,佳人北望1 小时前
C#程序入门
开发语言·windows·c#
江太翁1 小时前
mediapipe流水线分析 三
android·mediapipe
与火星的孩子对话2 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
coding随想2 小时前
JavaScript中的BOM:Window对象全解析
开发语言·javascript·ecmascript
念九_ysl3 小时前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
yaoxin5211233 小时前
124. Java 泛型 - 有界类型参数
java·开发语言