Jackson

annotation

JsonSubTypes

特定のフィールドの値によってサブクラスへ割り当てる。

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes(
        JsonSubTypes.Type(EventA::class, name = "a"),
        JsonSubTypes.Type(EventB::class, name = "b"),
        JsonSubTypes.Type(EventC::class, name = "c"))
open class Event(
    val type: String,
    val version: Int
)

class EventA(
    version: Int
) : Event(
    type = "a",
    version = version
)

// ...EventB, EventCの実装は省略

Enum

Enumクラス側をこのような実装にする。

enum class Color(@get:JsonValue val value: Int) {
    Red(1),
    Blue(2);

    companion object {
        @JsonCreator
        @JvmStatic
        fun of(value: Int) = values().find { it.value == value } ?: throw IllegalArgumentException()
    }
}

LinkedHashMapを任意のクラスに変換する

convertValueを使う。

val mapper = jacksonObjectMapper()
mapper.convertValue<Hoge>(anyValue)