Java Jackson 仅序列化接口方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18654293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:53:10  来源:igfitidea点击:

Hymanson serialize only interface methods

javajsonserializationHymanson

提问by Jordi P.S.

I have one object Awith some methods ma, mb, mcand this object implements an interface Bwith only maand mb.

我有一个对象A有一些方法mambmc并且这个对象实现了一个只有mamb的接口B

When I serialize BI expect only maand mbas a json response but I get as well mc.

当我序列化B 时,我只希望mamb作为json响应,但我也得到了mc

I'd like to automatize this behaviour so that all the classes I serialize get serialized based on the interface and not on the implementation.

我想自动化这种行为,以便我序列化的所有类都基于接口而不是实现进行序列化。

How should I do that?

我该怎么做?

Example:

例子:

public interface Interf {
    public boolean isNo();

    public int getCountI();

    public long getLonGuis();
}

Implementation:

执行:

public class Impl implements Interf {

    private final String patata = "Patata";

    private final Integer count = 231321;

    private final Boolean yes = true;

    private final boolean no = false;

    private final int countI = 23;

    private final long lonGuis = 4324523423423423432L;

    public String getPatata() {
        return patata;
    }


    public Integer getCount() {
        return count;
    }


    public Boolean getYes() {
        return yes;
    }


    public boolean isNo() {
        return no;
    }


    public int getCountI() {
        return countI;
    }

    public long getLonGuis() {
        return lonGuis;
    }

}

Serialization:

序列化:

    ObjectMapper mapper = new ObjectMapper();

    Interf interf = new Impl();
    String str = mapper.writeValueAsString(interf);

    System.out.println(str);

Response:

回复:

 {
    "patata": "Patata",
    "count": 231321,
    "yes": true,
    "no": false,
    "countI": 23,
    "lonGuis": 4324523423423423500
} 

Expected response:

预期回应:

 {
    "no": false,
    "countI": 23,
    "lonGuis": 4324523423423423500
 } 

采纳答案by broc.seib

Just annotate your interface such that Hymanson constructs data fields according to the interface's class and not the underlying object's class.

只需注释您的接口,以便 Hymanson 根据接口的类而不是底层对象的类来构造数据字段。

@JsonSerialize(as=Interf.class)
public interface Interf {
  public boolean isNo();
  public int getCountI();
  public long getLonGuis();
}

回答by Lu55

You have two options:

您有两个选择:

1) put @JsonSerializeannotation on your interface (see @broc.seib answer)

1)@JsonSerialize在您的界面上添加注释(请参阅@broc.seib 答案

2) or use specific writer for the serialization (as of Hymanson 2.9.6):

2) 或使用特定的 writer 进行序列化(从 Hymanson 2.9.6 开始):

ObjectMapper mapper = new ObjectMapper();
String str = mapper.writerFor(Interf.class).writeValueAsString(interf);