杰克逊:如何省略嵌套对象内部的字段

时间:2018-07-01 19:08:15

标签: java spring serialization jackson filtering

我有一个类似pojo的对象,具有以下结构:

@JsonFilter("MyFilter")
public MyDTO {
   public int id;
   public List<MyNestedDTO> nestedDTO;

   public MyNestedDTO {
       public int id;
       public String name;

       ... 
   }

   ...
}

我想从序列化输出中完全省略名称字段。我这样使用SimpleBeanPropertyFilter

ObjectMapper mapper = new ObjectMapper();
PropertyFilter columnFilter = new SimpleBeanPropertyFilter() {
   @Override
   public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer)
   throws Exception {
      if (include(writer)) {
         if (writer.getName().equalsIgnoreCase("nestedDTO")) {
                        return;
         }
         writer.serializeAsField(pojo, jgen, provider);
      } else if (!jgen.canOmitFields()) {
         writer.serializeAsOmittedField(pojo, jgen, provider);
      }
   }
   ...
};
FilterProvider filters = new SimpleFilterProvider().addFilter("MyFilter", columnFilter);

String result = mapper.writer(filters).writeValueAsString(MyDTOObj);

我看到通过这种nestedDTO.name实现,我无法捕捉serializeAsField()字段序列化的瞬间。请向我解释如何获得它。

1 个答案:

答案 0 :(得分:0)

如果要跳过字段的序列化/反序列化,只需使用@JsonIgnore进行注释:

public MyDTO {
   public int id;
   public List<MyNestedDTO> nestedDTO;

   public MyNestedDTO {
       public int id;
       @JsonIgnore
       public String name;

       ... 
   }

   ...
}