Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Deserializer for one custom field?

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

like image 503
hvgotcodes Avatar asked Dec 06 '16 17:12

hvgotcodes


People also ask

What is Jackson deserializer?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations. It's one of the most widely used libraries for this task, and runs under the hood of many other frameworks.

Does Jackson require default constructor?

Jackson uses default (no argument) constructor to create object and then sets value using setters. so you only need @NoArgsConstructor and @Setter.

Does Jackson use reflection?

Jackson is a framework that provides the means to read and write objects to and from JSON. Typically, it tries to use built in support for common classes and simple types. It will also use a default serializer based on reflection to write the JSON, but will need some guidance for more complex custom objects.


1 Answers

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.

like image 146
kleash Avatar answered Sep 17 '22 11:09

kleash