提问者:小点点

Jackson:如何仅序列化带注释的属性


我想在使用Jackson时定义我的自定义序列化策略(包括哪些字段)。我知道,我可以使用视图/过滤器来做到这一点,但它引入了非常糟糕的事情-使用字段名的字符串表示,这会自动启用自动重构问题。

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


共2个答案

匿名用户

如果禁用所有自动检测,它应该只序列化已注释的属性——无论是属性本身还是getter。下面是一个简单的例子:

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

匿名用户

如果您想在不为特定类型配置映射器的情况下这样做:

@JsonAutoDetect(
    fieldVisibility = Visibility.NONE,
    setterVisibility = Visibility.NONE,
    getterVisibility = Visibility.NONE,
    isGetterVisibility = Visibility.NONE,
    creatorVisibility = Visibility.NONE
)
public class BlahClass {
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("email")
    private String email;
}