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}")
相关推荐
爱吃烤鸡翅的酸菜鱼12 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
aningxiaoxixi38 分钟前
Android 之 audiotrack
android
枷锁—sha40 分钟前
【DVWA系列】——CSRF——Medium详细教程
android·服务器·前端·web安全·网络安全·csrf
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
Cao_Shixin攻城狮4 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发7 小时前
Eclipse 生成 jar 包
开发语言
呼啦啦呼啦啦啦啦啦啦7 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf