如果属性名称不等于字段名称,则Jackson自定义序列化程序序列化字段两次 [英] Jackson custom serializer serialize field twice if property name not equal field name

查看:556
本文介绍了如果属性名称不等于字段名称,则Jackson自定义序列化程序序列化字段两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用自定义序列化,如果属性名称不等于字段名称,则会产生意外效果。
为什么该字段被序列化两次?

If you use custom serialization, you can get an unexpected effect if property name not equal to field name. Why the field is serialized twice?

我的代码示例:

class Mode {
    @JsonProperty("mode")
    @JsonSerialize(using = ModeSerializer.class)
    private boolean isPublic;

    public Mode(boolean isPublic) {
        this.isPublic = isPublic;
    }

    public boolean isPublic() {
        return isPublic;
    }
}

这里我的自定义字段序列化器:

Here my custom field serializer:

class ModeSerializer extends JsonSerializer<Boolean> {

        @Override
        public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
            String out = "private";
            if (value) {
                out = "public";
            }
            gen.writeString(out);
        }
    }

此处测试:

public class Test {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Mode mode = new Mode(true);
        String toJson = mapper.writeValueAsString(mode);
        System.out.println(toJson);
    }
}

因此我收到:

{"public":true,"mode":"public"}

我做错了什么?

推荐答案

感谢您的详细解答。$
你绝对正确我需要隔离getter Public,这不仅可以重命名这个方法,还可以使用@JsonIgnore注释方法。
喜欢这个:

Thanks for the detailed answer.
You are absolutely right I need to isolate getter Public, and this can do not only with renaming this method, but also using the annotation @JsonIgnore to the method. Like this:

class Mode {
    @JsonProperty("mode")
    @JsonSerialize(using = ModeSerializer.class)
    private boolean isPublic;

    public Mode(boolean isPublic) {
        this.isPublic = isPublic;
    }

    @JsonIgnore
    public boolean isPublic() {
        return isPublic;
    }
}

这对我有用。

这篇关于如果属性名称不等于字段名称,则Jackson自定义序列化程序序列化字段两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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