如何将Kotlin数据类对象转换为地图? [英] How to convert a Kotlin data class object to map?

查看:101
本文介绍了如何将Kotlin数据类对象转换为地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何简单的方法或任何标准库方法通过属性名称将Kotlin数据类对象转换为其属性的地图/字典?可以避免反射吗?

Is there any easy way or any standard library method to convert a Kotlin data class object to a map/dictionary of it's properties by property names? Can reflection be avoided?

推荐答案

我使用的是jackson方法,但是对于第一次序列化(在此处查看基准测试)

I was using the jackson method, but turns out the performance of this is terrible on Android for first serialization (github issue here). And its dramatically worse for older android versions, (see benchmarks here)

但是您可以使用Gson更快地完成此操作.双向转换如下所示:

But you can do this much faster with Gson. Conversion in both directions shown here:

val gson = Gson()

//convert a data class to a map
fun <T> T.serializeToMap(): Map<String, Any> {
    return convert()
}

//convert a map to a data class
inline fun <reified T> Map<String, Any>.toDataClass(): T {
    return convert()
}

//convert an object of type I to type O
inline fun <I, reified O> I.convert(): O {
    val json = gson.toJson(this)
    return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

这篇关于如何将Kotlin数据类对象转换为地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆