Custom deserializer recursively calls `deserialize` method

20 views
Skip to first unread message

ilker cam

unread,
May 22, 2019, 3:40:28 PM5/22/19
to jackson-user
Hi,

I have a property which can be an integer or an object without any explicit `type` property. I tried to use JsonDeserialize annotation and provide a custom deserializer;

data class Report(val measures: List<IntOrMeasure>)

@JsonDeserialize(using=IntOrMeasureDeserializer::class)
sealed class IntOrMeasure {
    data class MeasureDefinition(val collection : DataMappingHttpService.RakamCollection, val name : String) : IntOrMeasure()
    data class MeasureId(val id : Int) : IntOrMeasure()
}

class IntOrMeasureDeserializer : JsonDeserializer<IntOrMeasure>() {
    override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): IntOrMeasure {
        return if(p!!.currentToken().isNumeric) {
            p.readValueAs(IntOrMeasure.MeasureId::class.java)
        } else {
            p.readValueAs(IntOrMeasure.MeasureDefinition::class.java)
        }
    }
}

p.readValueAs(IntOrMeasure.MeasureId::class.java) recursively calls deserialize again thus resulting with overflow.
Any insights are appreciated, thanks.

Tatu Saloranta

unread,
May 22, 2019, 3:44:50 PM5/22/19
to jackson-user
What happens when you call `readValueAs()` is that parser calls back
to ObjectMapper linked to parser, asks for deserializer registered for
given type, calls its `deserialize()` method. So the question would be
what specifically is registered to handle `MeasureId` or
`MeasureDefinition`. If it's the same deserializer implementation for
some reason (maybe due to subclassing?) then there'd be infinite loop.

I hope this helps,

-+ Tatu +-

遗迹

unread,
Jun 7, 2019, 2:21:30 PM6/7/19
to jackson-user
The same problem. I'm using kotlin too. The subclasses has inherit @Deserializer annotation again. So the ObjectMapper fall in an infinite-loop.
Reply all
Reply to author
Forward
0 new messages