Venky Venky - 1 year ago 82
Java Question

Json custom deserializer stuck in infinite recursion

Implemented a custom deserializer to deserialize a JSON by the following way. but mapper.treeToValue is causing to call the code infinite number of times.

public class MyDeserializer extends StdDeserializer<MyResource> {
public myResourcedeserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
MyResource resource = null;
Class<? extends MyResource > clazz = null;
ObjectMapper mapper = (ObjectMapper) parser.getCodec();
ObjectNode node = (ObjectNode) mapper.readTree(parser);

Iterator<Map.Entry<String, JsonNode>> elementsIterator = node.fields();

while (elementsIterator.hasNext()) {
Map.Entry<String, JsonNode> element =;
if(element.getValue().asInt() == 1)
clazz = SpecificResource.class;
return mapper.treeToValue(node,clazz);

After executing mapper.treeToValue, control again goes back myResourcedeserialize method and executing it infinite number of times and causing stackOverFlowError.

Any suggestions please?

Answer Source

We have faced similar situation and this solution is based on that: The custom de-serializer is used to parse JSON polymorphically without using type attribute

Lets call the polymorphic classes as BaseResource (base class), SubResource1, SubResource2.

BaseResource has annotation to specify which CustomSerializer class

public class BaseResource{

So on SubResource1 and SubResource2, we add annotations to not use the CustomDeserialzer.class by using JsonDeserialer.None.class

public class SubResource1 extends BaseResource{


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download