一尘不染

杰克逊:如何仅序列化带注释的属性

json

我想在使用Jackson时定义我的自定义序列化策略(要包括的字段)。我知道,我可以使用视图/过滤器来做到这一点,但是它引入了非常不好的一件事-
使用字段名称的字符串表示形式,这会自动导致自动重构出现问题。

如何迫使Jackson序列化仅带注释的属性,仅此而已?


阅读 211

收藏
2020-07-27

共1个答案

一尘不染

如果禁用所有自动检测,则应仅序列化已注释的属性-无论是属性本身还是吸气剂。这是一个简单的例子:

private ObjectMapper om;

@Before
public void setUp() throws Exception {
    om = new ObjectMapper();
    // disable auto detection
    om.disable(MapperFeature.AUTO_DETECT_CREATORS,
            MapperFeature.AUTO_DETECT_FIELDS,
            MapperFeature.AUTO_DETECT_GETTERS,
            MapperFeature.AUTO_DETECT_IS_GETTERS);
    // if you want to prevent an exception when classes have no annotated properties
    om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}

@Test
public void test() throws Exception {
    BlahClass blahClass = new BlahClass(5, "email", true);
    String s = om.writeValueAsString(blahClass);
    System.out.println(s);
}

public static class BlahClass {
    @JsonProperty("id")
    public Integer id;
    @JsonProperty("email")
    public String email;
    public boolean isThing;

    public BlahClass(Integer id, String email, boolean thing) {
        this.id = id;
        this.email = email;
        isThing = thing;
    }
}
2020-07-27