使用Jackson依次反序列化 [英] sequentially deserialize using Jackson

查看:434
本文介绍了使用Jackson依次反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Jackson进行序列化和反序列化的value对象.

I have a value object serialized and deserialized using Jackson.

VO具有两个字段:x和y.但是调用setY仅在设置x时才有意义.有什么方法可以确保在反序列化过程中setX的调用早于setY的调用?

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?

推荐答案

您只能通过为POJO(VO)类实现自定义解串器来做到这一点.假设您的POJO类看起来像这样:

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

在那之后,您必须告诉Jackson使用上述解串器.例如,通过这种方式:

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

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

对我来说,您的setY阻止了设置方法的责任.您应该避免在setter方法中隐藏类逻辑的情况.更好的解决方案是创建一种新的计算方法:

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

这篇关于使用Jackson依次反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆