sequentially deserialize using Jackson

心不动则不痛 提交于 2020-01-14 06:40:43

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/19151396/sequentially-deserialize-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!