What’s the best way to convert a Map(or MutableMap...
# announcements
c
What’s the best way to convert a Map(or MutableMap) into a Data Class?
l
how about json?
c
It is something that I have defined, but I will need to have a data class in the end. I just used the MutableMap to be able to add dynamic values to it, but in the end I will need a Data class
l
if your types are dynamic, then what would that data class look like? also why are you trying to use dynamic types in a type safe language in the first place?
c
I have something like this:
Copy code
data class StatusObject (
    val event: String
)
then I have
Copy code
var myMutableMap: MutableMap<String, Any?> = mutableMapOf("event" to "default")
After that I receive an array of objects and will map through them to add them to
myMutableMap
Copy code
receivedArrayWithObjects.forEach {
            myMutableMap[it.header.name] = it.status.name
        }
But in the end, I need to return a StatusObject I’m having this problem because I’m bringing code from Javascript to Kotlin
r
If you can annotate your data class
@Serializable
you can use
kotlinx.serialization
library for this.
c
Yeah, I can. And after that how can I use it?
note that
Mapper
class was renamed to
Properties
in serialization 0.20.0
c
Thanks!
r
also look at the issue I've created a few days ago https://github.com/Kotlin/kotlinx.serialization/issues/743
m
you could also delegate; makes you better in control of the types in your class
Copy code
class StatusObject(mapInput: MutableMap<String, Any?>) {
    val event: String by mapInput
    var otherVariable: YourComplexType? by mapInput
}
advantage of this method is that you can keep adding to the map after creation and the corresponding variables will update accordingly.
😯 1