嵌套对象的杰克逊序列化 [英] jackson serialization of nested objects

查看:83
本文介绍了嵌套对象的杰克逊序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过对象的接口对对象进行杰克逊序列化.

I have problem with jackson serialization of object by its interface.

我上课

class Point implements PointView {

    private String id;

    private String name;

    public Point() {

    }

    public Point(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

}

实现

interface PointView {
    String getId();
}

并上课

class Map implements MapView {

    private String id;

    private String name;

    private Point point;

    public Map() {

    }

    public Map(String id, String name, Point point) {
        this.id = id;
        this.name = name;
        this.point = point;
    }

    @Override
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @JsonSerialize(as = PointView.class)
    public Point getPoint() {
        return point;
    }

}

实现

interface MapView {
    String getId();
    Point getPoint();
}

并上课

class Container {

    private Map map;

    public Container() {

    }

    public Container(Map map) {
        this.map = map;
    }

    @JsonSerialize(as = MapView.class)
    public Map getMap() {
        return map;
    }
}

我想用Jackson序列化Container并得到结果

I want serialize Container with Jackson and get result

{"map":{"id":"mapId","point":{"id":"pointId"}}}

但实际上我得到了结果

{"map":{"id":"mapId","point":{"id":"pointId","name":"pointName"}}}

尽管我在Map(@JsonSerialize(as = PointView.class))中指定了Point的序列化类型,但在嵌套对象"point"中具有属性"name"的

.接口PointView没有方法getName,但是结果中存在Point的字段"name".

that have property "name" in nested object "point" although I specified serializition type of Point in Map (@JsonSerialize(as = PointView.class)). Interface PointView dont have method getName, but in result exists field "name" of Point.

如果我从类Container中的getMap方法中删除注释(@JsonSerialize(as = MapView.class)),则会得到结果

If I remove annotation (@JsonSerialize(as = MapView.class)) from method getMap in class Container I get result

{"map":{"id":"mapId","name":"mapName","point":{"id":"pointId"}}}

现在点没有属性名称",但是地图具有属性.

Now point dont have property "name", but map have.

我如何获得结果

{"map":{"id":"mapId","point":{"id":"pointId"}}}

?

推荐答案

要获得所需结果,还必须在接口中用@JsonSerialize

To get the desired result also the same method in interface must be annotated by @JsonSerialize

interface MapView {
    String getId();
    @JsonSerialize(as = PointView.class)
    Point getPoint();
}

这篇关于嵌套对象的杰克逊序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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