18

我有一个对象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
 } 
4

2 回答 2

25

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

@JsonSerialize(as=Interf.class)
public interface Interf {
  public boolean isNo();
  public int getCountI();
  public long getLonGuis();
}
于 2015-06-24T15:31:28.480 回答
8

你有两个选择:

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

2)或使用特定的作家进行序列化(从杰克逊 2.9.6 开始):

ObjectMapper mapper = new ObjectMapper();
String str = mapper.writerFor(Interf.class).writeValueAsString(interf);
于 2019-02-08T14:47:05.333 回答