0

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?

Neel
  • 2,100
  • 5
  • 24
  • 47

1 Answers1

2

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();
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • Ziober Thanks for your response! What if setting x should modify the value of x? – Neel Oct 04 '13 at 03:08
  • I do not understand your question. Could you, please, give me more details? – Michał Ziober Oct 04 '13 at 07:44
  • Ziober: Sorry, that was a typo - I meant: "what if setting 'y' should modify the value of 'x'? In that case, calculateSomething gets invoked inside the setter for 'y' because the code is expected to be tightly coupled. – Neel Oct 05 '13 at 14:47
  • It looks like you want to do more than only set 'Y' value. I think, set method should only set value. If you want to recalculate another property in set method, you can add new method for this. – Michał Ziober Oct 05 '13 at 23:21