【问题标题】:Jackson - annotate the class to be excluded from serialization when some property meets specific criteriaJackson - 当某些属性满足特定条件时,注释要从序列化中排除的类
【发布时间】:2013-05-10 06:11:41
【问题描述】:

我有以下用例,假设我有一个带有 WHEEL 对象列表的对象 CAR

class Car{
   List<Wheel> wheels;
   //getters and setters..
}

现在假设 Wheel 类有一个属性 boolean isWinterTyre;

我想知道是否有任何注释,可能是自定义序列化的东西或其他东西,以某种方式注释 Car 类或 Wheel 类本身以排除所有具有属性的轮对象 isWinterTyre = true 包含在' wheels' 列表,同时将我的 Java 'Car' 实例序列化为 JSON 表示。

【问题讨论】:

  • 你在寻找什么 json 输出?
  • json结构会一样,我只是想根据它们的属性跳过一些轮子。

标签: java json jackson


【解决方案1】:

应该可以使用自定义序列化。见教程here。

@JsonSerialize(using = CustomSerializer.class)
class Wheel {
   //getters and setters..
}


public class CustomSerializer extends JsonSerializer<Wheel> {

    @Override
    public void serialize(Wheel value, JsonGenerator generator, 
        SerializerProvider provider) throws IOException,
            JsonProcessingException {
                 if(value.getSomething() == something) {
                     //Output Wheel using the generator
                 } else {
                     //skip it
                 }
            }
}

【讨论】:

    猜你喜欢
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2013-01-14
    相关资源
    最近更新 更多