How to convert a Kotlin data class object to map?

前端 未结 6 1550
一个人的身影
一个人的身影 2020-12-09 02:39

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 avoid

6条回答
  •  无人及你
    2020-12-09 03:26

    Kpropmap is a reflection-based library that attempts to make working with Kotlin data classes and Maps easier. It has the following capabilities that are relevant:

    • Can transform maps to and from data classes, though note if all you need is converting from a data class to a Map, just use reflection directly as per @KenFehling's answer.
    data class Foo(val a: Int, val b: Int)
    
    // Data class to Map
    val propMap = propMapOf(foo)
    
    // Map to data class
    val foo1 = propMap.deserialize()
    
    • Can read and write Map data in a type-safe way by using the data class KProperty's for type information.

    • Given a data class and a Map, can do other neat things like detect changed values and extraneous Map keys that don't have corresponding data class properties.

    • Represent "partial" data classes (kind of like lenses). For example, say your backend model contains a Foo with 3 required immutable properties represented as vals. However, you want to provide an API to patch Foo instances. As it is a patch, the API consumer will only send the updated properties. The REST API layer for this obviously cannot deserialize directly to the Foo data class, but it can accept the patch as a Map. Use kpropmap to validate that the Map has the correct types, and apply the changes from the Map to a copy of the model instance:

    data class Foo(val a: Int, val b: Int, val c: Int)
    
    val f = Foo(1, 2, 3)
    val p = propMapOf("b" to 5)
    
    val f1 = p.applyProps(f) // f1 = Foo(1, 5, 3)
    

    Disclaimer: I am the author.

提交回复
热议问题