hello! i'm new to this library, can anyone point m...
# serialization
j
hello! i'm new to this library, can anyone point me to the right doc or an example to help me figure out how to handle de/serialization in cases where the data comes in a very specific format like this:
Copy code
{
  "op": "op type",
  "data": {
    "id": "",
    "name": ""
  }
}
for some context, the server utilizes both http and websockets. the op is something like
GetSite
or
GetUser
and the data block is an array of the op's values. right now i'm running into an issue where it can't figure out what to use for the data block when receiving a response on the websocket. i'm starting to feel like it won't be possible to utilize one set of classes for both http/ws. i got the following to work but something about it just feels hacky 😓
Copy code
@Serializable
class SampleRequest {
    private val op = "GetThing"
    var data: Data

    constructor(auth: String?): super() {
        data = Data(auth)
    }

    @Serializable
    class Data(
        val auth: String?
    )
}
Copy code
@Serializable
class SampleResponse {
    private val op = "GetThing"
    var data: Data
    
    constructor(id: Int, name: String): super() {
        data = Data(id, name)
    }
    
    @Serializable
    class Data(
        val id: Int,
        val name: String
    )
}
my one hope is i'm just missing something really obvious here, but the fireworks have started and i can no longer concentrate lol
i believe i figured it out, it was something obvious. i'll reply to myself later with what i did
t
Have you looked over the Polymorphism guide? https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md Perhaps it provides some strategies to tackle what you're trying to accomplish?
j
@travis yep. my first iteration pre-1.0.0 utilized that, but the way i had it set up just felt bloated. each class contained an internal data class with the real properties of the class. it certainly worked and if I only needed to use websockets I probably would have ran with it but I needed a separate request and response class for each operation.
now I'm using a request and response class and the op is inserted via the function call rather than being pulled from a class. data is a generic.
the server API I'm hitting has some oddities as far as how stuff is structured which was throwing me off, but it's a community developed open source project so the typical planning probably didn't happen :)