Jackson:如何仅序列化带注释的属性 [英] Jackson: how to serialize only annotated properties

查看:37
本文介绍了Jackson:如何仅序列化带注释的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to define my custom serialization strategy (which fields to include), while using Jackson. I know, that I can do it with views/filters, but it introduces very bad thing - using string-representation of field names, which automatically enables problems with auto-refactoring.

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

How do I force Jackson into serializing only annotated properties and nothing more?

推荐答案

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

If you disable all auto-detection it should only serialize the properties that you have annotated--whether it be the properties themselves or the getters. Here's a simple example:

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

这篇关于Jackson:如何仅序列化带注释的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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