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}")
相关推荐
Q_Q5110082851 小时前
python的校园研招网系统
开发语言·spring boot·python·django·flask·node.js·php
wstcl1 小时前
安卓app、微信小程序等访问多个api时等待提示调用与关闭问题
android·微信小程序·webapi
louisgeek2 小时前
Android Studio 打印中文乱码
android
眼镜会飞3 小时前
Flutter 3.x新版android端的build.gradle.kts文件配置arm64-v8a和armeabi-v7a等
android·前端·flutter
vocal3 小时前
【我的安卓第一课】Activity 的伙伴 Fragment
android
Nayuta4 小时前
字节跳动「移动 OS 部门」招聘安卓工程师,AI+OS 方向
android
Cyclic10014 小时前
IOS购买订阅通知信息解析说明Java
java·开发语言·ios
00后程序员张4 小时前
iOS 应用上架常见问题与解决方案,多工具组合的实战经验
android·ios·小程序·https·uni-app·iphone·webview
AI视觉网奇4 小时前
麒麟系统播放图片 速度比较
开发语言·python·pygame
恋猫de小郭4 小时前
Flutter 小技巧之有趣的 UI 骨架屏框架 skeletonizer
android·前端·flutter