利用Kotlin与Gson解析Json转换指定对象实体数据

1、Gson将Json数据转换成指定对象

  • Gradle配置
   implementation 'com.google.code.gson:gson:2.8.6'
  • Maven配置


    com.google.code.gson
    gson
    2.8.6


2、Json数据

{
    "code": 1, 
    "msg": "成功", 
    "data": {
        "id": "44ebb879c2bf4072bae4b927cffd9de4", 
        "createById": "admin", 
        "createTime": "2022-01-08 11:10:58", 
        "updateTime": "2022-01-08 11:10:58",  
        "title": "爱学习的蹭蹭的", 
        "blogUrl": "https://www.jianshu.com/u/830d5fabc5ad", 
        "detail": "", 
        "authorName": "爱学习的蹭蹭"
    }
}

3、转换的实体

  • ResponseVo 与DataVo类
data class ResponseVo(
    var code: Int,
    var msg: String,
    var data: DataVo
) {
}

data class DataVo(
    var id: String,
    var authorName: String,
    var createById: String,
    var title: String,
    var blogUrl: String,
    var updateTime: String,
    var createTime: String,
    var detail: String,
) {

}

4、代码实现

  • JsonUtils工具类
  • 参考文章:https://juejin.cn/post/7049983952496361503
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * 
 * 参考文章:https://juejin.cn/post/7049983952496361503
 */
open class JsonUtils() {
 
    /**
     * fromJson2List
     */
    inline fun  fromJson2List(json: String) = fromJson>(json)

    /**
     * fromJson
     */
    inline fun  fromJson(json: String): T? {
        return try {
            val type = object : TypeToken() {}.type
            return Gson().fromJson(json, type)
        } catch (e: Exception) {
            println("try exception,${e.message}")
            null
        }
    }
}

5、main代码测试

fun main() {
  
    var json :String ="{\n" +
            "    \"code\": 1, \n" +
            "    \"msg\": \"成功\", \n" +
            "    \"data\": {\n" +
            "        \"id\": \"44ebb879c2bf4072bae4b927cffd9de4\", \n" +
            "        \"createById\": \"admin\", \n" +
            "        \"createTime\": \"2019-10-25 11:10:58\", \n" +
            "        \"updateTime\": \"2019-10-25 11:10:58\",  \n" +
            "        \"title\": \"爱学习的蹭蹭的\", \n" +
            "        \"blogUrl\": \"https://www.jianshu.com/u/830d5fabc5ad\", \n" +
            "        \"detail\": \"\", \n" +
            "        \"authorName\": \"爱学习的蹭蹭\"\n" +
            "    }\n" +
            "}"

    var responseVo = JsonUtils().fromJson(json)

    //输出结果
    println(responseVo?.data?.authorName)
    println(responseVo?.data?.blogUrl)
    println(responseVo?.data?.detail)

}

你可能感兴趣的:(利用Kotlin与Gson解析Json转换指定对象实体数据)