用带有该字段的注释的Jackson进行序列化时,如何完全忽略该字段的值? [英] How to ignore field totally by its value when serializing with Jackson with annotation on that field?

查看:94
本文介绍了用带有该字段的注释的Jackson进行序列化时,如何完全忽略该字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎相同的问题,但可接受的答案不符合一般需求.具有简单的类和自定义序列化器,如:

Almost the same question but the accepted answer does not fit the general need. Having Simple class and custom serializer like:

示例类

@Getter
@Setter
public class ExampleClass {
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonSerialize(using = StringSerializer.class)
    private String stringNull;        
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonSerialize(using = StringSerializer.class)
    private String stringOk = "ok";
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonSerialize(converter = StringSerializer.class)
    private String stringNotOk = "notOk";        
}

自定义序列化器

@SuppressWarnings("serial")
public static class StringSerializer extends StdSerializer<String> {
    public StringSerializer() {
        super(String.class);
    }
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) 
            throws IOException {
        if(value != null && value.equals("ok")) {
            gen.writeString(value);
        }
    }
}

所以我只想打印出等于"ok"的元素.但如果不等于"ok",我不想打印任何东西.除stringNotOk之外,其他都可以正常工作.像这样调用ObjectMappper时:

So I only want to print out elements that are equal to "ok" but if not equal to "ok" I do not want to print anything. Works fine except for stringNotOk. When calling ObjectMappper like:

new ObjectMapper().writeValueAsString(new ExampleClass());

它会产生坏"的信号. JSON:

it produces "bad" JSON:

{"stringOk":"ok","stringNotOk"}

{"stringOk":"ok","stringNotOk"}

还有其他方法,还是可以避免将序列化程序提升到类级别,并为每个具有此类字段的类(考虑帐户字段名称等)单独创建它?

Is there any other way or can I can avoid to raise the serializer to class level and create it separately for each class having such field na taking account field name etc...?

例如,我可以以某种方式还原"吗?返回并删除名称"stringNotOk",来自已经编写的JSON?

Can I - for example - somehow "revert" back and remove the name "stringNotOk" from already written JSON?

如何以一种通用的方式做到这一点,以便仅使用一个序列化程序和在所需字段上的注释?

How could this be made in a generic way so that just one serializer and an annotation on needed fields were used?

推荐答案

我认为您正在寻找类似的东西

I think you are looking for something like

@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = OkFilter.class)

public class OkFilter {

  @Override
  public boolean equals(Object obj) {
     //your logic for finding 'ok' value here
  }
}

在这里您可以阅读有关此内容的更多信息 https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html

Here you can read more about this https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html

这篇关于用带有该字段的注释的Jackson进行序列化时,如何完全忽略该字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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