2015-10-15 33 views
2

我有问题与杰克逊序列化的对象的接口。杰克逊嵌套对象的序列化

我有类

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

我想序列化集装箱与杰克逊并获得导致

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

但事实上,我得到的结果

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

,在嵌套的对象具有属性“名”虽然我在地图中指定了序列化类型的Point(点号)(@JsonSerialize(as = PointView.class))。接口PointView不具有方法getName,但在结果中存在字段“名称”的点。

如果我删除类集装箱从法的GetMap注释(@JsonSerialize(as = MapView.class))我得到的结果

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

现在点不要有“名称”属性,但地图都有。

我怎样才能导致

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

+0

我发现这个问题的解决方案进行注释。 Annotation @JsonSerialize也必须在接口'Map getView {String getId(); @JsonSerialize(as = PointView。类)getPoint(); }' –

+0

最好:你写你的解答作为答案,并且打勾是正确的。 (只要有可能) –

回答

2

要获得期望的结果也是在接口同样的方法必须由@JsonSerialize

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

您可以注释的方法是这样的:

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

或者,如果你想在其他人在此情况下使用特定的序列化,但正常的序列化,你可以使用一个@JsonView(见doc)。

之所以它的序列化出来的name是,实例具有存取getName(),即使接口没有。

+0

是的。 '@ JsonIgnore'起作用。但是类Point可能是其他类的一部分,该序列化必须包含Point的“name”属性。我只想通过它的接口来指定类的接受。可能吗? –

+0

'@ JsonView'有问题。如果类Point将有其他几个嵌套对象,并且每个嵌套对象都有它们的嵌套对象。使用'@ JsonView',我必须将此注释设置为所有嵌套对象,以便将它们包含在序列化中。考虑到嵌套对象的链可能非常大,这并不好。我希望每个类都可以为每个嵌套对象设置序列化视图 –

+0

您可以创建对象的[深层复制](https://en.wikipedia.org/wiki/Object_copying#Deep_copy),并为其Point对象的名称字段为空。 – Bohemian

0

是的,你可以使用

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

无论是在实现类(如上),或在具有价值属性。