kotlin : Gson 的内联函数

在类里面写完内联就能直接扩展Gson库的方法,很好用,一行代码:

private inline fun  Gson.fromJson(json: String?) = fromJson(json, T::class.java)

完整代码: 

class PushListenerService : FirebaseMessagingService() {
    override fun onMessageReceived(message: RemoteMessage?) {
        val params = message?.data
        val jsonObject = JSONObject(params)
        val jsonContent = jsonObject.toString()
        LogUtils.outputLogFile(LogUtils.NOTIFICATION_LOG_FILE_PATH, "json RemoteMessage:" + jsonContent)
        //receive roaster push notice
        val intent = Intent(this, PushNotificationDetailActivity::class.java)
        if (message?.data != null) {
            for ((key, value) in message.data) {
                intent.putExtra(key, value)
            }
            //insert
            val pb = PushNoticeBean()
            pb.title = message.data["title"]
            LogUtils.outputLogFile(LogUtils.NOTIFICATION_LOG_FILE_PATH, "pb title:" + pb.title)
            pb.content = message.data["message"]
            LogUtils.outputLogFile(LogUtils.NOTIFICATION_LOG_FILE_PATH, "pb.content:" + pb.content)
            pb.noticeIconUrl = message.data["icon"]
            LogUtils.outputLogFile(LogUtils.NOTIFICATION_LOG_FILE_PATH, "pb.noticeIconUrl:" + pb.noticeIconUrl)
            pb.id = java.lang.Long.valueOf(Objects.requireNonNull(message.data["id"]))
            LogUtils.outputLogFile(LogUtils.NOTIFICATION_LOG_FILE_PATH, "pb.id:" + pb.id)
            val currentTime = System.currentTimeMillis()
            pb.date = Utils.inst.timeToString(currentTime)

            val darjeelString = message.data["darjeeling_silent"]
            val pushDarjeelingBean = Gson().fromJson(darjeelString)
            pb.url = pushDarjeelingBean.url
            pb.imageUrl = pushDarjeelingBean.imageUrl
            DaoUtils.addPushData(pb)
            //set weburl
            intent.putExtra("bean", pb)
        }
        Rtoaster.onPushMessageReceived(message, intent, R.mipmap.icon)
    }

    private inline fun  Gson.fromJson(json: String?) = fromJson(json, T::class.java)
}

 

你可能感兴趣的:(kotlin : Gson 的内联函数)