如何在Kotlin中与Gson一起使用TypeToken +泛型(How to use TypeToken + generics with Gson in Kotlin)

class RosPublishResponse {

var msg:T? =null

    var id: String? =null

    var topic: String? =null

    var op: String? =null

}

open class BaseSubscribeMsg(var header: Header? =null)

data class RobotStatus(val robot_status: Int? = -1) : BaseSubscribeMsg(){}

创建内联方法

inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type

使用

val resp ="{\"topic\": \"/robot_system_status\", \"msg\": {\"header\": {\"stamp\": {\"secs\": 1577094994, \"nsecs\": 417498327}, \"frame_id\": \"\", \"seq\": 14869}, \"robot_status\": 10}, \"op\": \"publish\"}"

val robotStatus= Gson().fromJson<RosPublishResponse<RobotStatus>>(resp)

进过封装后不用每次都去手动new TypeToken

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容