Is it possible to handle a json which can vary in its property types like this:
{
"someValue": 123
}
and
{
"someValue": "123"
}
into a single @Serializable
object? Any is not serializable so I'm looking for some intermediate converter which would unify the values into the same type (e.g. 123.toString() to habe them both strings).
If you wanna get someValue: Int
, it's gonna be parsed fine by default in both cases.
If it should be String
, you can use isLenient
option to make it work:
Removes JSON specification restriction (RFC-4627) and makes parser more liberal to the malformed input. In lenient mode quoted boolean literals, and unquoted string literals are allowed.
val json = Json {
isLenient = true
}
If you can't use both these, e.g. you wanna have strict rules for all other classes used with the same parser configuration, you can build your own class, e.g. parsing int and returning string:
@Serializable
@JvmInline
value class StringSerializableFromInt(private val intValue: Int) {
val value get() = intValue.toString()
}
or just building a custom serializer for more complex logic - check out more about building custom serializers in documentation