Hi, I have a very cursed json response that I want...
# serialization
s
Hi, I have a very cursed json response that I want to deserialize that looks (roughly) like this (I can send a real-world example json response if you'd like, but there's a lot of other stuff in there I don't care about, and it makes the json very annoying to read as there are several tens of thousands of lines of garbage if you format the json):
Copy code
{
  "player": {
    "foo": "abcd",
    "bar": "abcd",
    "selected_killstreak_0": "data",
    "selected_killstreak_1": "data",
    "selected_killstreak_2": "data",
    "selected_killstreak_3": "data"
  }
}
and, I would like to deserialize it into a class that looks like the following:
Copy code
@Serializable
data class Player(
    val foo: String,
    val bar: String,
    val selectedKillStreaks: List<String>
                 )
is this possible? Or, would I have to deserialize it into a class like this:
Copy code
@Serializable
data class Player(
    val foo: String,
    val bar: String,
    @SerialName("selected_killstreak_0")
    val selectedKillstreak0: String,
    @SerialName("selected_killstreak_1")
    val selectedKillstreak1: String,
    @SerialName("selected_killstreak_2")
    val selectedKillstreak2: String,
    @SerialName("selected_killstreak_3")
    val selectedKillstreak3: String,
                 )
(note: in some cases there will always be a known number of items in the form
name_[n]
, where
[n]
is the index, however in other cases there are an arbitrary number of items in that same form. I would like to ideally be able to deserialize for an arbitrary length) yes, I know that this json is very cursed, but there's nothing I can do about it
a
that’s pretty cursed! KxS can handle it though, by using a JsonTransformingSerializer
main.kt.cpp
s
also btw, the
selected_killsteak_n
values aren't necessarily in order. sometimes they can be in the order,
selected_killstreak_2
,
selected_killstreak_3
,
selected_killstreak_1
,
selected_killstreak_0
(because why not!)
also, this pattern of
name_[n]
occurs many times in the json I want to decode, and I'd prefer to avoid having to re-write this every time I need to deserialized a cursed list like this would there be any way to make it a json transforming serializer for
List<T>
(it's not always string, and sometimes can be an object) so that I can just do smth like
Copy code
// ...
@SerialName("selected_killstreak_")
@Serializable(CursedListDeserializer::class)
val selectedKillstreak: List<String>,
// ...
a
you could stick a
selectedKillStreaks.sortedBy { it.key }
in there somewhere to make the sorting work
you can play around with the PlayerSerializer above to try and make it more generic/reusable. You could make it an abstract class, and the subclasses could re-use the code.
e
or if this happens all over your input data, perhaps you could use a custom format