Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read field from parent node in custom Jackson Deserializer

Have a look at the following input JSON:

{
    "importantKey": "123xyz",
    "nested": {
        // more stuff goes here.
    }
}

Nested is represented by an interface that has several different implementations. The point is, in order to figure out which implementation should be used for deserialization, I need to check importantKey's value.

My current solution is to deserialize the whole thing at once:

@Override
public Foo deserialize(JsonParser jp, DeserializationContext dc) 
            throws IOException, JsonProcessingException {

    ObjectMapper objectMapper = (ObjectMapper) jp.getCodec();
    ObjectNode objectNode = objectMapper.readTree(jp);
    String importantKey = objectNode.findValue("importantKey").asText();

    JsonNode nestedNode = objectNode.findValue("nested");
    NestedInterface nested;
    nested = objectMapper.treeToValue(nestedNode, findNestedImplFor(importantKey));

    // construct containing Foo and so on ...
}

This works but for several different reasons (specific to my use case) it would be a lot cooler if there was a Deserializer just for nested that somehow could read or had access to fields from the outer object.

I'm running jackson 2.8.x in a dropwizard context.

Does someone have an idea? Thanks in advance!

like image 464
Doe Johnson Avatar asked Oct 22 '16 13:10

Doe Johnson


1 Answers

You can access it through the DeserializationContext like so

Object parent = dc.getParser().getParsingContext().getCurrentValue();

Then cast it to the appropriate POJO type that has the 'importantKey' field.

like image 132
PaulMooney Avatar answered Oct 15 '22 11:10

PaulMooney