I am getting the following error whilst trying to map an incoming REST-api result in Json to an object :
failed to invoke private kotlinx.serialization.json.jsonelement() with no args
After some searching the problem seems to be that I am trying to instantiate a Value() object whilst it's a sealed class. Now I'm not sure how to solve this ?
data class Device (
@SerializedName(value="DeviceSettings")
val deviceSettings: Map<String, Value>? = null,
@SerializedName(value="Id")
val id: String
)
sealed class Value {
class BoolValue(val value: Boolean) : Value()
class DoubleValue(val value: Double) : Value()
class IntegerValue(val value: Long) : Value()
class StringValue(val value: String) : Value()
}
The problem occurs when the deviceSettings mapping is being constructed. Because it might contain several types of data the Value sealed class is defined. But as mentioned this will simply crash whilst beings parsed...
The idea is that the DeviceSettings Map is dynamic, that's why it's not actually parsed into a predefined data class for example ! It might contain a single key:value pair but there might also be thirty !
@cutiko Thats correct, Hereby some of the received json :
"DeviceSettings": {
"ToneLevel": 80.0,
"AutoLogging": false,
"OrientationLandscape": false,
"AudioDuration": 2500.0,
"ShoutLevel": 1.0,
"SipExtension": 0.0,
"SipServerAuthenticationKey": "",
"SipServerPort": 5060.0,
"SipServerUri": ""
}
You will have to write a custom
TypeAdapterwhich peeks at the type of the JSON data and depending on it chooses the correctValuesubclass to instantiate. For example:You would then register the adapter on a
GsonBuilderlike this:There are however a few things to consider, so you might have to adjust this code:
-0? With the code above it would be parsed asLongand the-sign would be lost. Maybe you want to parse it asDouble-0.0instead.Doubleor do you have a different logic for deciding what is aDoubleor aLong?kotlinx.serializationis not clear.