简体   繁体   中英

how to call default parser (registered in mapper) from custom deserializer

I need to provide custom deserialization of the Map and then each Property object has to be serialized by default serializer. This map is part of another object:

class PropertiesHolder {
    Map<String, Property> properties;
}

I've defined mixin for the PropertiesHolder class:

class PropertiesHolderMixIn {
    @JsonSerialize(using=PropertiesSerializer.class)
    @JsonDeserialize(using=PropertiesDeserializer.class)
    Map<String, Property> properties;
}

I have also mixin for Property class. The ObjectMapper initialization:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.setMixInAnnotation(Property.class, PropertyMixIn.class);
module.setMixInAnnotation(PropertiesHolder.class, PropertiesHolderMixIn.class);
mapper.registerModule(module);

My deserializer:

class PropertiesDeserializer extends JsonDeserializer<Map<String, Property>> {
    public Map<String, Property> deserialize(JsonParser jp, DeserializationContext ctxt) throws ... {
        ArrayNode node = (ArrayNode) jp.readValueAsTree();
        for (int i = 0, size = node.size() ; i < size ; i++) {
            ObjectNode jn = (ObjectNode) node.get(i);
            String key = jn.get("propertyName").textValue();
            String value = jn.get("propertyValue").toString();
            ... HERE I need to call registered deserializer for Property class over value ...
        }
    }
}

I've looked at How do I call the default deserializer from a custom deserializer in Jackson , but it doesn't work form me ... it ends with NPE. Also the solution described in the post creates deserializer for the outer class which for me is defined as mixin and I don't want to create deserializer for this class.

Please, point me to a solution. Where can I get default deserializer for the Property object?

Thanks

Solution is this line of code:

ObjectMapper mapper = (ObjectMapper)jp.getCodec();

Call this method within "deserialize(...)" method. So the important (for me) code fragment is:

ObjectMapper mapper = (ObjectMapper)jp.getCodec();
Property property = mapper.readValue(jn.get("propertyValue").toString(), Property.class));

Found on this blog.

The problem is that you will need a fully constructed default deserializer; and this requires that one gets built, and then your deserializer gets access to it. DeserializationContext is not something you should either create or change; it will be provided by ObjectMapper

So all you need to write in the deserialize() method is:

ObjectMapper mapper = (ObjectMapper)jp.getCodec();
Property property = mapper.readValue(jn.get("propertyValue").toString(), Property.class));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM