如何在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 Gson.fromJson(json: String) = this.fromJson(json, object: TypeToken() {}.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>(resp)

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

你可能感兴趣的:(如何在Kotlin中与Gson一起使用TypeToken +泛型(How to use TypeToken + generics with Gson in Kotlin))