Thread
#serialization
    h

    Helio

    1 year ago
    Hello everyone, 👋🏽 I’ve had a look at Kotlinx.Serialization documentation, and also looked for examples, but I couldn’t find the best practice for the case I’m going to describe. I wonder if anyone would be able to provide any insight. Also, I’m not an advanced user of the library. I have an server that return a JSON Payload containing a single Status property:
    {
      "status": "OneOf<Pending|Queued|InProgress|Finished|NotBuilt>"
    }
    If I want to serialise it to Enum, I would have:
    @Serializable
    enum class Status {
        @SerialName("Pending") PENDING,
        @SerialName("Queued") QUEUED,
        @SerialName("InProgress") IN_PROGRESS,
        @SerialName("Finished") FINISHED,
        @SerialName("NotBuilt") NOT_BUILT,
    }
    
    @Serializable
    data class ServerResponseModel(val status: Status)
    However, when I get a response from the server, let’s say
    InProgress
    all I need to do is build a new Model and return the status as being
    IN_PROGRESS
    . What would be the best way to achieve that? Do I need to write a custom serialisation in this case? Also, does it makes sense to create an
    Enum class
    for
    ServerResponseModel
    ? Thanks for your assistance.
    p

    Paul Griffith

    1 year ago
    I think an enum would be fine, and it should "just work" (no custom serializers required) based on your example
    If you might in the future have additional information (that's different) in each response type, you could use a sealed class hierarchy instead - then each inner class would be able to hold different information (I've found that's a pretty common pattern with REST APIs driven by more dynamic languages)
    h

    Helio

    1 year ago
    Thanks for your help Paul! I’ll probably have to do the sealed class hierarchy as you mentioned… I was trying to avoid that since it requires a bit more of boilerplate.
    If I stick with enums, I would need to have 2
    enum classes
    . The 1st enum would map the responses from Server, which returns:
    InProgress
    . And another that enum that maps a response from Server to
    InProgress
    to
    IN_PROGRESS
    which is the response I want to send.
    p

    Paul Griffith

    1 year ago
    :hmm: I haven't actually used it myself, but maybe you could have one enum, but use the new
    @JsonNames
    annotation?
    h

    Helio

    1 year ago
    Thanks for pointing this. 🙂
    @Paul Griffith, not sure if you would be interested, but I ended up doing something like this as a workaround. 😦