杰克逊仅序列化接口方法

Jor*_*.S. 11 java serialization json jackson

我有一个对象一些方法毫安,MB,MC和该对象实现了接口毫安MB.

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

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

我该怎么办?

例:

public interface Interf {
    public boolean isNo();

    public int getCountI();

    public long getLonGuis();
}
Run Code Online (Sandbox Code Playgroud)

执行:

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

}
Run Code Online (Sandbox Code Playgroud)

连载:

    ObjectMapper mapper = new ObjectMapper();

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

    System.out.println(str);
Run Code Online (Sandbox Code Playgroud)

响应:

 {
    "patata": "Patata",
    "count": 231321,
    "yes": true,
    "no": false,
    "countI": 23,
    "lonGuis": 4324523423423423500
} 
Run Code Online (Sandbox Code Playgroud)

预期回复:

 {
    "no": false,
    "countI": 23,
    "lonGuis": 4324523423423423500
 } 
Run Code Online (Sandbox Code Playgroud)

bro*_*eib 14

只需注释您的界面,以便Jackson根据接口的类而不是底层对象的类构造数据字段.

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

  • 如果我的 impl 类有多个接口,并且我想根据接口中定义的 getter 序列化对象,该怎么办? (2认同)
  • 我想从不同的服务返回不同的接口。 (2认同)
  • 那行不通,无论接口是什么,Jackson 总是序列化底层实现。 (2认同)

Lu5*_*u55 6

您有两个选择:

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

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

ObjectMapper mapper = new ObjectMapper();
String str = mapper.writerFor(Interf.class).writeValueAsString(interf);
Run Code Online (Sandbox Code Playgroud)