使用Jackson顺序反序列化

时间:2013-10-03 05:24:10

标签: json jackson deserialization json-deserialization

我有一个使用Jackson序列化和反序列化的值对象。

VO有两个字段:x和y。但是只有在设置了x时才调用setY。有没有什么办法可以确保在反序列化期间比setY更早地调用setX?

1 个答案:

答案 0 :(得分:2)

只能通过为POJO(VO)类实现自定义反序列化器来实现。假设您的POJO类看起来像这样:

class Point {

    private int x;
    private int y;

    //getters, setters, toString
}

现在,您可以实现反序列化器。你可以这样做:

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;
    }
}

之后,你必须告诉Jackson使用上面的解串器。例如,以这种方式:

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

对我来说,你的setY刹车制定方法责任。你应该避免在setter方法中隐藏类逻辑的情况。更好的解决方案是创建新的计算方法:

point.setX(10);
point.setY(11);
point.calculateSomething();