Question

I have a value object serialized and deserialized using Jackson.

The VO has two fields: x and y. But invoking setY makes sense only when x is set. Is there any way I can make sure that setX is invoked earlier than setY during de-serialization?

Was it helpful?

Solution

You can do it only by implementing custom deserializer for your POJO (VO) class. Let assume that you POJO class looks like this:

class Point {

    private int x;
    private int y;

    //getters, setters, toString
}

Now, you can implement deserializer. You can do it in this way:

class PointJsonDeserializer extends JsonDeserializer<Point> {

    @Override
    public Point deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        InnerPoint root = jp.readValueAs(InnerPoint.class);

        Point point = new Point();
        point.setX(root.x);
        point.setY(root.y);

        return point;

    }

    private static class InnerPoint {
        public int x;
        public int y;
    }
}

After that, you have to tell Jackson to use above deserializer. For example, in this way:

@JsonDeserialize(using = PointJsonDeserializer.class)
class Point {
     ...
}

For me, your setY brakes setter method responsibility. You should avoid situation like that where you hide class logic in setter method. Better solution is creating new method for calculations:

point.setX(10);
point.setY(11);
point.calculateSomething();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top