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

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

问题描述

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

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

推荐答案

我使用的是 jackson 方法,但结果证明在 Android 上第一次序列化的性能很差 (github 问题在这里).对于旧的 android 版本,它的情况要糟糕得多,(在此处查看基准)

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:

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

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)
}

//example usage
data class Person(val name: String, val age: Int)

fun main() {

    val person = Person("Tom Hanley", 99)

    val map = mapOf(
        "name" to "Tom Hanley", 
        "age" to 99
    )

    val personAsMap: Map<String, Any> = person.serializeToMap()

    val mapAsPerson: Person = map.toDataClass()
}

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

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