杰克逊仅序列化接口方法 [英] Jackson serialize only interface methods

查看:125
本文介绍了杰克逊仅序列化接口方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象 A ,其中包含 ma mb mc 等方法,此对象实现了一个接口 B 只有 ma mb

I have one object A with some methods ma, mb, mc and this object implements an interface B with only ma and mb.

当我序列化 B时我希望只有 ma mb 作为json响应,但我也可以 mc

When I serialize B I expect only ma and mb as a json response but I get as well 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.

如何我应该这样做吗?

示例:

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
 } 


推荐答案

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

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

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

这篇关于杰克逊仅序列化接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆