Venky Venky - 1 day ago 4
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> {
@Override
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 = elementsIterator.next();
if(element.getKey().equals("typeId"))
{
if(element.getValue().asInt() == 1)
{
clazz = SpecificResource.class;
break;
}
}
}
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

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

@JsonDeserialze(using=CustomDeserializer.class)
public class BaseResource{
......
}

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

@JsonDeserialze(using=JsonDeserialer.None.class)
public class SubResource1 extends BaseResource{
......
}

Reference: http://www.robinhowlett.com/blog/2015/03/19/custom-jackson-polymorphic-deserialization-without-type-metadata/

Comments