嵌套对象的杰克逊序列化

jackson serialization of nested objects

我在通过其接口对对象进行 jackson 序列化时遇到问题。

我有class

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

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

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 并得到结果

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

但实际上我得到了结果

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

在嵌套对象 "point" 中有 属性 "name",尽管我在 Map (@JsonSerialize(as = PointView.class)) 中指定了 Point 的序列化类型。接口 PointView 没有方法 getName,但结果存在 Point.

字段 "name"

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

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

现在点没有属性"name",但是地图有。

我怎样才能得到结果

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

?

你可以这样注释方法:

@JsonIgnore
public String getName() {
    return name;
}

或者,如果您希望在此用例中进行特定序列化,但在其他用例中进行正常序列化,则可以使用 @JsonView(参见 doc)。

它序列化 name 的原因是 实例 具有访问器 getName(),即使接口没有。

是的,你可以使用

@JsonSerialize(as=MyInterface.class)
public class ConcreteClass implements MyInterface { .... }

实现 class(如上所述),或 属性 具有价值。

要获得所需的结果,接口中的相同方法也必须用 @JsonSerialize

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