杰克逊仅序列化接口方法

2022-09-02 09:30:01

我有一个对象A,其中包含一些方法mambmc,并且该对象实现了仅具有mamb的接口B

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

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

我应该怎么做?

例:

public interface Interf {
    public boolean isNo();

    public int getCountI();

    public long getLonGuis();
}

实现:

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

}

序列化:

    ObjectMapper mapper = new ObjectMapper();

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

    System.out.println(str);

响应:

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

预期响应:

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

答案 1

只需对接口进行注释,以便 Jackson 根据接口的类而不是基础对象的类构造数据字段。

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

答案 2

您有两种选择:

1)在你的界面上放置注释(参见@broc.seib答案@JsonSerialize)

2)或使用特定的编写器进行序列化(从Jackson 2.9.6开始):

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