简体   繁体   English

如何跳过杰克逊中特定值的特定字段的序列化?

[英]How do I skip serialization of specific fields for specific values in jackson?

So I have 所以我有

class Foo {
  double bar = -30000.0
  double baz = 200
}

-30000.0

is not actually a valid value, it's the default value emitted by the hardware, realistically this should be a null value. 实际上不是一个有效值,它是硬件发出的默认值,实际上这应该是一个空值。 I don't want to serialize this value, instead I'd like to omit the key completely if it's this value (the same way if I'd set skip nulls). 我不想序列化此值,相反,如果它是此值,我想完全省略键(如果我设置跳过空值,则采用相同的方式)。 problem is, baz can also be be -30000.0 but there it's valid. 问题是,baz也可以是-30000.0,但是在那里有效。 There is actually more conditional logic depending on the field/value, but this is the simplest example. 实际上,取决于字段/值的条件逻辑更多,但这是最简单的示例。

I feel like I want to write this 我觉得我想写这个

class Foo {
   @Skip30k
   double bar = -30000.0
   double baz = -30000.0
}

the output of this should be 这个的输出应该是

"{"baz":-30000.0}"

I've read baeldung's post and other things, but it seems like my options are on a custom type (this is a primitive) or global. 我已经阅读了baeldung的文章和其他内容,但似乎我的选择是在自定义类型(这是原始类型)或全局类型上。 How can I achieve this custom serialization? 如何实现此自定义序列化?

You may want to try @JsonInclude : 您可能要尝试@JsonInclude

@JsonInclude(value = JsonInclude.Include.CUSTOM, 
             valueFilter = Skip30kFilter.class)
private double bar;
public class Skip30kFilter {

    @Override
    public boolean equals(Object other) {

        double value = (Double) other;
        return value > -30000.0;
    }
}

You also may consider a custom annotation and a serializer, as described in this answer . 您还可以考虑自定义注释和序列化程序,如本答案所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM