Prostotak
Prostotak

Reputation: 37

Is it possible in kotlin serialization without using intermediate options to immediately convert Map <String, Any> to a model

This case is in the JS version (Properties.decodeFromMap (map)), but for android, I have not seen.

It can also be solved using Jackson

The object in which I should get a rather complex type, the approximate form of the fields is much larger

data class BaseModel (val value: String,val options: Options,val type: Type ...)

The main thing I need to get directly from Map <String, Any> in BaseModel

Upvotes: 1

Views: 223

Answers (2)

Prostotak
Prostotak

Reputation: 37

I think it's better to use the properties from the kotlinx-serialization-properties package, it turns out that it is also distributed for android

Upvotes: 0

D. Kupra
D. Kupra

Reputation: 373

This was quite a ride through deep kotlin but I got a minimal example.

data class BaseModel(var a:Int, var b:String)

...

//during onCreate 
val map=mutableMapOf<String,Any>()
map.put("a",1)
map.put("b","b")
test(map)

...
fun test(map:MutableMap<String,Any>){
        val params=BaseModel::class.constructors.toList()[0].parameters.associateBy({ it }, { map.get(it.name) })
        val bm=BaseModel::class.constructors.toList()[0].callBy(params)
        println(bm.a)
        println(bm.b)
    }


And it prints 1 and b as expected.

A little caveat though, you have to have kotlin-reflect.jar in the classpath, which you can add by clicking an alert if you're using Android Studio. But if you don't add that dependency, you won't get a compile time error or any warnings in your IDE; the error won't be caught until runtime.

Upvotes: 1

Related Questions