Serialize JSON with Klaxon

284 Views Asked by At

I'm trying to develop a system which alows serializing/deserializing of JSON for multiple types of classes in Kotlin. For deserialization I'm usung klaxon, but I also want to use it for serializstion. I've done some research on that, but didn't get a concluseve answer.

So, can I do that? If so, how can it be done? Or should I use other library for this purpose?

Here's my code

package com.pineapple.threadio

import com.beust.klaxon.Klaxon
import com.beust.klaxon.TypeAdapter
import com.beust.klaxon.TypeFor
import kotlin.reflect.KClass

// Frame types

@TypeFor(field = "id", adapter = FrameTypeAdapter::class)
open class BasicFrame(val id: String)
class Ping : BasicFrame("0x0000")
class TransactionRequest : BasicFrame("0x0001")
class TransactionAccept : BasicFrame("0x0002")
class TransactionDeny(val deny_reason: String) : BasicFrame("0x0003")

// Frame processing
class Frame(
    @TypeFor(field = "id", adapter = FrameTypeAdapter::class)
    val id: String,

    val frame: BasicFrame
)

class FrameTypeAdapter : TypeAdapter<BasicFrame> {
    override fun classFor(id: Any): KClass<out BasicFrame> = when (id as String) {
        "0x0000" -> Ping::class
        "0x0001" -> TransactionRequest::class
        "0x0002" -> TransactionAccept::class
        "0x0003" -> TransactionDeny::class
        else -> throw IllegalArgumentException("Unknown frame ID: $id")
    }
}

// Actual parsing, straight from klaxon's docs
val frame = Klaxon().parseArray<Frame>(json)
1

There are 1 best solutions below

1
On

@TypeFor(field = "id", adapter = FrameTypeAdapter::class) annotation should be placed on BasicFrame class. It's redundant on places where you put it.