I have to deserialize JSON, where a field can be a...
# serialization
l
I have to deserialize JSON, where a field can be any JSON primitive (e.g. null, int, string, double, boolean). Can I just define it in my data model as
JsonPrimitive
and it will work out-of-the-box?
Copy code
@Serializable
data class Response(
    val field: JsonPrimitive
)
Responses can be:
Copy code
{ "field":134 }
{ "field":false }
{ "field":null }
Although
JsonPrimitive
always contains a String, so it doesn't seem to work.
So I probably need to write a custom serializer for this?
h
l
Thanks! Can I somehow check the subtype of the parsed
JsonPrimitive
?
If it contains an Int, String etc.
h
Basically I do
Copy code
if (jsonPrimitive.contentOrNull == null) {
    // It's null
} else if (jsonPrimitive.booleanOrNull != null) {
    // Boolean
} else if (jsonPrimitive.doubleOrNull != null) {
    // It's a Double
} ...
l
ok, that should work as well
Thanks!
h
Check MEmbers & Extensions in the docs link.
l
Yes, I see there are all extensions which I need
h
I don't get why the extensions are hidden as default 🙂
t
don't forget to shame whoever designed that api enough that they never do it again
l
😄
It's an open source project 😉 Flagsmith
😆 1
h
I've seen this enough times to accept that it is some sort of pattern used by some developers. While cumbersome to work with, you do get to say that your app can handle polymorphic data. 🙂
t
I think the pattern is more a byproduct of javascript/node letting people play fast and loose with typing. at least that is what my gut tells me
and/or python
h
Maybe. But then I did see this back in the days when we used XML instead. 🙂
Copy code
<field>12345</field>
<field>some string</field>
<field>true</field>
Handling boolean in those cases was interesting...