在序列化myObject时,我要在运行时确定属性类别中的null属性或不包含null属性。什么是最好的方法?
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;
}
如果您使用的是杰克逊2.8,则可以使用新的" config Reverrides"功能(在此处讨论的f.ex上讨论了F.EX),以指定注释的等效词,例如:
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
定义一次,而进一步的更改将不会产生效果。如果您需要不同配置的映射器,则需要创建不同的实例。
有几种可能性,具体取决于您的运行时决策控制的精细。
-
如果行为是在运行时完全自定义的,则可以使用自己的自定义过滤器,可以执行复杂的决定来序列化字段。过滤器看起来像这样:
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);
-
如果 class 的属性的行为相同,请带有
的属性该属性@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyObject { @JsonInclude(JsonInclude.Include.NON_NULL) private String property1; private String property2; }
-
如果对于完整类(例如属性)的行为是相同的,请使用
@JsonInclude(JsonInclude.Include.NON_NULL)
或配置config config conform confride over rides Staxman描述@JsonInclude(JsonInclude.Include.NON_NULL) public class Attributes { private String property1; private String property2; }
-
如果的行为对于当前映射的所有类别:配置映射器,就像Franjavi一样
您可以在映射器中更改该行为:
if (noNull) {
mapper.setSerializationInclusion(Include.NON_NULL);
} else {
mapper.setSerializationInclusion(Include.ALWAYS);
}