如何让Jackson序列化可空ZonedDateTime时输出null值?
解决方案
1. 强制输出Null字段(最直接)
问题核心是Jackson默认会忽略值为null的字段(若全局或类级别配置了JsonInclude.Include.NON_NULL),只需在目标字段上添加@JsonInclude(JsonInclude.Include.ALWAYS)注解,强制Jackson输出该字段:
@JsonInclude(JsonInclude.Include.ALWAYS) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = ElasticSearchConstants.ZONED_DATE_TIME_FORMAT) @JsonSerialize(using = ZonedDateTimeSerializer.class) @JsonDeserialize(using = ZonedDateTimeDeserializerFromIsoText.class) private ZonedDateTime myVariable;
此时ZonedDateTimeSerializer的父类会自动处理null值,输出预期的"myVariable": null。
2. 全局配置输出Null字段
如果需要所有null字段都被输出,可修改Jackson的ObjectMapper全局配置:
ObjectMapper objectMapper = new ObjectMapper(); // 全局设置序列化时包含所有字段,包括null值 objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
这种方式无需修改字段注解,适合全局统一需求。
3. 指定Null值序列化器
若ZonedDateTimeSerializer在特定版本中无法处理null,可通过@JsonSerialize的nullsUsing属性指定Jackson自带的null序列化器:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = ElasticSearchConstants.ZONED_DATE_TIME_FORMAT) @JsonSerialize(using = ZonedDateTimeSerializer.class, nullsUsing = NullSerializer.class) @JsonDeserialize(using = ZonedDateTimeDeserializerFromIsoText.class) private ZonedDateTime myVariable;
NullSerializer(全类名com.fasterxml.jackson.databind.ser.std.NullSerializer)会输出标准的null值。
4. 自定义Null安全的序列化器
如果以上方法都不适用,可自定义序列化器继承ZonedDateTimeSerializer,显式处理null场景:
public class NullSafeZonedDateTimeSerializer extends ZonedDateTimeSerializer { public NullSafeZonedDateTimeSerializer() { super(DateTimeFormatter.ofPattern(ElasticSearchConstants.ZONED_DATE_TIME_FORMAT)); } @Override public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { if (value == null) { gen.writeNull(); } else { super.serialize(value, gen, serializers); } } }
然后替换字段上的序列化器:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = ElasticSearchConstants.ZONED_DATE_TIME_FORMAT) @JsonSerialize(using = NullSafeZonedDateTimeSerializer.class) @JsonDeserialize(using = ZonedDateTimeDeserializerFromIsoText.class) private ZonedDateTime myVariable;
内容的提问来源于stack exchange,提问作者Dakkaron
相关产品推荐
相关产品推荐

