Stack Overflow when using Jackson to convert JsonNode to an instance of a specific class

I’m writing a incoming packet deserializer. All incoming packets is encoded in JSON, and its type depends on field “post_type”.

  • If it’s “meta_event”, there must be a field called “meta_event_type”, which can be “lifecycle” or “heartbeat”.
    • If it’s “lifecycle”, there must be a field called “sub_type”, which can be “enable”, “disable” or “connect”.
    • If it’s “heartbeat”, there must be 2 fields called “status” and “interval” (millseconds).
  • If it’s “message_event”, …
  • Remaining many other situations …

Here are 2 legal packet strings:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"sub_type": "connect",
"meta_event_type": "lifecycle",
"post_type": "meta_event"
}
</code>
<code>{ "sub_type": "connect", "meta_event_type": "lifecycle", "post_type": "meta_event" } </code>
{
  "sub_type": "connect",
  "meta_event_type": "lifecycle",
  "post_type": "meta_event"
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"meta_event_type": "heartbeat",
"interval": 5000,
"status": {
"good": true,
...
},
"post_type": "meta_event"
}
</code>
<code>{ "meta_event_type": "heartbeat", "interval": 5000, "status": { "good": true, ... }, "post_type": "meta_event" } </code>
{
  "meta_event_type": "heartbeat",
  "interval": 5000,
  "status": {
    "good": true,
    ...
  },
  "post_type": "meta_event"
}

I wrote corresponding POJO classes for them, and add a specific deserializers to choose sub-class deserializers based on some fields:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@JsonDeserialize(using = EventDataDeserializer::class)
sealed class EventData {
abstract val postType: String
}
object EventDataDeserializer : StdDeserializer<EventData>(EventData::class.java) {
private fun readResolve(): Any = EventDataDeserializer
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): EventData {
val node = p.readValueAsTree<ObjectNode>()
val mapper = p.codec as ObjectMapper
return when (val postType = node.getNotNull(POST_TYPE).asText()) {
META_EVENT -> node.deserializeTo<MetaEventData>(mapper)
// ...
else -> throw IllegalArgumentException("Unknown post type: $postType")
}
}
}
@JsonDeserialize(using = MetaEventDataDeserializer::class)
sealed class MetaEventData : EventData() {
abstract val metaEventType: String
}
data class LifecycleMetaEventData(
// "meta_event"
override val postType: String,
// "lifecycle"
override val metaEventType: String,
// "enable", "disable" or "connect"
@JsonProperty(SUB_TYPE)
val subType: String
) : MetaEventData()
data class HeartbeatEventData(
// "meta_event"
override val postType: String,
// "heartbeat"
override val metaEventType: String,
@JsonProperty(STATUS)
val status: Any?,
@JsonProperty(INTERVAL)
val interval: Long
) : MetaEventData()
object MetaEventDataDeserializer : StdDeserializer<MetaEventData>(MetaEventData::class.java) {
private fun readResolve(): Any = MetaEventDataDeserializer
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): MetaEventData {
val node = p.readValueAsTree<ObjectNode>()
val mapper = p.codec as ObjectMapper
return when (val subType = node.getNotNull(META_EVENT_TYPE).asText()) {
LIFECYCLE -> node.deserializeTo<LifecycleMetaEventData>(mapper)
HEARTBEAT -> node.deserializeTo<HeartbeatEventData>(mapper)
else -> throw IllegalArgumentException("Unexpected sub type: $subType")
}
}
}
</code>
<code>@JsonDeserialize(using = EventDataDeserializer::class) sealed class EventData { abstract val postType: String } object EventDataDeserializer : StdDeserializer<EventData>(EventData::class.java) { private fun readResolve(): Any = EventDataDeserializer override fun deserialize(p: JsonParser, ctxt: DeserializationContext): EventData { val node = p.readValueAsTree<ObjectNode>() val mapper = p.codec as ObjectMapper return when (val postType = node.getNotNull(POST_TYPE).asText()) { META_EVENT -> node.deserializeTo<MetaEventData>(mapper) // ... else -> throw IllegalArgumentException("Unknown post type: $postType") } } } @JsonDeserialize(using = MetaEventDataDeserializer::class) sealed class MetaEventData : EventData() { abstract val metaEventType: String } data class LifecycleMetaEventData( // "meta_event" override val postType: String, // "lifecycle" override val metaEventType: String, // "enable", "disable" or "connect" @JsonProperty(SUB_TYPE) val subType: String ) : MetaEventData() data class HeartbeatEventData( // "meta_event" override val postType: String, // "heartbeat" override val metaEventType: String, @JsonProperty(STATUS) val status: Any?, @JsonProperty(INTERVAL) val interval: Long ) : MetaEventData() object MetaEventDataDeserializer : StdDeserializer<MetaEventData>(MetaEventData::class.java) { private fun readResolve(): Any = MetaEventDataDeserializer override fun deserialize(p: JsonParser, ctxt: DeserializationContext): MetaEventData { val node = p.readValueAsTree<ObjectNode>() val mapper = p.codec as ObjectMapper return when (val subType = node.getNotNull(META_EVENT_TYPE).asText()) { LIFECYCLE -> node.deserializeTo<LifecycleMetaEventData>(mapper) HEARTBEAT -> node.deserializeTo<HeartbeatEventData>(mapper) else -> throw IllegalArgumentException("Unexpected sub type: $subType") } } } </code>
@JsonDeserialize(using = EventDataDeserializer::class)
sealed class EventData {
    abstract val postType: String
}

object EventDataDeserializer : StdDeserializer<EventData>(EventData::class.java) {
    private fun readResolve(): Any = EventDataDeserializer
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): EventData {
        val node = p.readValueAsTree<ObjectNode>()
        val mapper = p.codec as ObjectMapper

        return when (val postType = node.getNotNull(POST_TYPE).asText()) {
            META_EVENT -> node.deserializeTo<MetaEventData>(mapper)
            // ...
            else -> throw IllegalArgumentException("Unknown post type: $postType")
        }
    }
}

@JsonDeserialize(using = MetaEventDataDeserializer::class)
sealed class MetaEventData : EventData() {
    abstract val metaEventType: String
}

data class LifecycleMetaEventData(
    // "meta_event"
    override val postType: String,

    // "lifecycle"
    override val metaEventType: String,

    // "enable", "disable" or "connect"
    @JsonProperty(SUB_TYPE)
    val subType: String
) : MetaEventData()

data class HeartbeatEventData(
    // "meta_event"
    override val postType: String,

    // "heartbeat"
    override val metaEventType: String,

    @JsonProperty(STATUS)
    val status: Any?,

    @JsonProperty(INTERVAL)
    val interval: Long
) : MetaEventData()


object MetaEventDataDeserializer : StdDeserializer<MetaEventData>(MetaEventData::class.java) {
    private fun readResolve(): Any = MetaEventDataDeserializer
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): MetaEventData {
        val node = p.readValueAsTree<ObjectNode>()
        val mapper = p.codec as ObjectMapper

        return when (val subType = node.getNotNull(META_EVENT_TYPE).asText()) {
            LIFECYCLE -> node.deserializeTo<LifecycleMetaEventData>(mapper)
            HEARTBEAT -> node.deserializeTo<HeartbeatEventData>(mapper)
            else -> throw IllegalArgumentException("Unexpected sub type: $subType")
        }
    }
}

Functions getNotNull and deserializeTo<T> are some useful extension methods:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>fun JsonNode.getOptionalNullable(key: String) = get(key)
fun JsonNode.getOptionalNotNull(key: String) = when (this) {
is ObjectNode -> {
val result = get(key)
if (result === null && contains(key)) {
throw NullPointerException("The value of key '$key' is null.")
}
result
}
else -> throw IllegalStateException("The node is not an object node.")
}
fun JsonNode.getNullable(key: String) = when (this) {
is ObjectNode -> {
val result = get(key)
if (result === null && !contains(key)) {
throw NoSuchElementException("The value of key '$key' doesn't present.")
}
result
}
else -> throw IllegalStateException("The node is not an object node.")
}
fun JsonNode.getNotNull(key: String) =
getOptionalNotNull(key) ?: throw NullPointerException("The value of key '$key' is null.")
fun <T> JsonNode.deserializeTo(objectMapper: ObjectMapper, type: TypeReference<T>) = objectMapper.convertValue(this, type)
inline fun <reified T> JsonNode.deserializeTo(objectMapper: ObjectMapper) = deserializeTo(objectMapper, object : TypeReference<T>() {})
</code>
<code>fun JsonNode.getOptionalNullable(key: String) = get(key) fun JsonNode.getOptionalNotNull(key: String) = when (this) { is ObjectNode -> { val result = get(key) if (result === null && contains(key)) { throw NullPointerException("The value of key '$key' is null.") } result } else -> throw IllegalStateException("The node is not an object node.") } fun JsonNode.getNullable(key: String) = when (this) { is ObjectNode -> { val result = get(key) if (result === null && !contains(key)) { throw NoSuchElementException("The value of key '$key' doesn't present.") } result } else -> throw IllegalStateException("The node is not an object node.") } fun JsonNode.getNotNull(key: String) = getOptionalNotNull(key) ?: throw NullPointerException("The value of key '$key' is null.") fun <T> JsonNode.deserializeTo(objectMapper: ObjectMapper, type: TypeReference<T>) = objectMapper.convertValue(this, type) inline fun <reified T> JsonNode.deserializeTo(objectMapper: ObjectMapper) = deserializeTo(objectMapper, object : TypeReference<T>() {}) </code>
fun JsonNode.getOptionalNullable(key: String) = get(key)

fun JsonNode.getOptionalNotNull(key: String) = when (this) {
    is ObjectNode -> {
        val result = get(key)
        if (result === null && contains(key)) {
            throw NullPointerException("The value of key '$key' is null.")
        }
        result
    }

    else -> throw IllegalStateException("The node is not an object node.")
}

fun JsonNode.getNullable(key: String) = when (this) {
    is ObjectNode -> {
        val result = get(key)
        if (result === null && !contains(key)) {
            throw NoSuchElementException("The value of key '$key' doesn't present.")
        }
        result
    }

    else -> throw IllegalStateException("The node is not an object node.")
}

fun JsonNode.getNotNull(key: String) =
    getOptionalNotNull(key) ?: throw NullPointerException("The value of key '$key' is null.")

fun <T> JsonNode.deserializeTo(objectMapper: ObjectMapper, type: TypeReference<T>) = objectMapper.convertValue(this, type)

inline fun <reified T> JsonNode.deserializeTo(objectMapper: ObjectMapper) = deserializeTo(objectMapper, object : TypeReference<T>() {})

But StackOverflowError will be thrown when deserializing the first example json, because in MetaEventDataDeserializer, LIFECYCLE -> node.deserializeTo<LifecycleMetaEventData>(mapper) will make Jackson use MetaEventDataDeserializer to deserialize the node, instead of the default deserializer of LifecycleMetaEventData.

How to solve it gracefully?

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật