2016-11-26 44 views
0

在序列化MyObject时,我想在运行时决定属性类中包含或不包含空属性。什么是最好的方法来做到这一点?在运行时设置序列化属性

import com.fasterxml.jackson.annotation.JsonInclude; 
import lombok.Data; 

@Data 
@JsonInclude(JsonInclude.Include.NON_NULL) 
public class MyObject { 
    private String property1; 
    private DateTime property2; 
    private Attributes attributes; 
} 

@Data 
public class Attributes { 
    private String property1; 
    private String property2; 
} 

回答

0

你可以改变这种行为的映射:

if (noNull) { 
    mapper.setSerializationInclusion(Include.NON_NULL); 
} else { 
    mapper.setSerializationInclusion(Include.ALWAYS); 
} 
+0

但我需要做条件包括null只在'Attributes'类中,而不在'MyObject'类中。 – Shikhar

1

如果使用的是杰克逊2.8,你可以使用新的“配置覆盖”功能(在高级别讨论f.ex here) ,指定相当于注释的,就像这样:

mapper.configOverride(Attributes.class) 
    // first value for value itself (POJO); second value only relevant 
    // for structured types like Map/Collection/array/Optional 
    .setInclude(JsonInclude.Value.construct(Include.NON_NULL, null)); 

(与其他几个方面以前只可使用注释一起)

但是,请注意,与注释一样,此设置不是在初始设置后可以更改的设置:它必须定义为ObjectMapper一次,并且进一步的更改不会生效。 如果您需要配置不同的映射器,则需要创建不同的实例。

1

有几种可能性,这取决于您的运行时决策控制所需的细粒度。

  • 如果的行为是完全自定义在运行时,您可以使用自己的自定义过滤器,可以做复杂的决定,要么序列字段或不是。过滤器会是这个样子:

    PropertyFilter myFilter = new SimpleBeanPropertyFilter() { 
        @Override public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception { 
    
         boolean needsSerialization = needsSerializationBasedOnAdvancedRuntimeDecision((MyValueObject) pojo, writer.getName()); 
    
          if (needsSerialization){ 
           writer.serializeAsField(pojo, jgen, provider); 
          } 
    
        } 
    
        @Override protected boolean include(BeanPropertyWriter writer) { return true; } 
        @Override protected boolean include(PropertyWriter writer) { return true; } 
    }; 
    

    如果您的序列决定,可在财产属性的基础上进行处理,例如:

    private boolean needsSerializationBasedOnAdvancedRuntimeDecision(MyValueObject myValueObject, String name) { 
        return !"property1".equals(name) || (myValueObject.getProperty1() == null && property1NullSerializationEnabled); 
    } 
    

    ,您就可以申请你想如下过滤器:

    FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", myFilter); 
    
    String json = new ObjectMapper().writer(filters).writeValueAsString(myValueObject); 
    
  • 如果行为是一类的属性相同,标注该属性@JsonInclude(JsonInclude.Include.NON_NULL)

    ​​
  • 如果的行为是一个完整的类相同的(例如属性),配置类,无论是与@JsonInclude(JsonInclude.Include.NON_NULL)或与配置覆盖StaxMan描述

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    public class Attributes { 
        private String property1; 
        private String property2; 
    } 
    
  • 如果行为是当前映射所有类相同的:配置映射,如franjavi

相关问题