18

I believe we need a custom deserializer to do something specific with one field on our class. It appears once I do this, I am now responsible for deserializing all the other fields. Is there a way to have Jackson deserialize all the fields except the one I am concerned with here?

public class ThingDeseralizer extends StdDeserializer<Thing> {
    @Override
    public Thing deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = p.getCodec();
        JsonNode node = oc.readTree(p);

        String special = node.get("special").asText();

        Thing thing = new Thing()
        thing.doSomethignWithSpecial(special)
        return thing;
    }
}

Thanx

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236

1 Answers1

16

On your field in POJO add @JsonDeserialize(using = ThingDeseralizer.class) annotation.

This will tell Jackson how to deserialze that particular field, rest all will go as default.

tmucha
  • 689
  • 1
  • 4
  • 19
kleash
  • 1,211
  • 1
  • 12
  • 31
  • Yes I just discovered this. Hypothetically speaking is there a way to do this with a single deserializer on the class? I imagine there has to be some method on the super class, or a different class to extend, that will fill out everything and let me override just what I want. – hvgotcodes Dec 06 '16 at 18:15
  • You mean to use deserializer on whole class? Than as you said you have to define all fields. But that's easy too, check this answer: [link](http://stackoverflow.com/questions/7161638/how-do-i-use-a-custom-serializer-with-jackson/7168386#7168386) – kleash Dec 06 '16 at 18:24
  • what's the relevant part in that link? – hvgotcodes Dec 06 '16 at 19:02
  • @hvgotcodes For serialization, `JsonSerializable` interface would do this, but unfortunately deserialization does not have similar support -- this is due to difficulties in defining suitable API: during serialization there is already an instance to call method on, but this is not the case for deserialization. – StaxMan Dec 07 '16 at 04:04
  • @hvgotcodes That custom ItemSerializer class to serialize the whole Item class. It's easy to serialize integer, string etc. – kleash Dec 07 '16 at 05:19