重写 JsonSerializer 序列化方法,如下所示。
public class NullSerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
// any JSON value you want...
jgen.writeString("");
}
}
然后您可以将NullSerializer
自定义对象映射器设置为默认值:
public class CustomJacksonObjectMapper extends ObjectMapper {
public CustomJacksonObjectMapper() {
super();
DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new NullSerializer());
this.setSerializerProvider(sp);
}
}
@JsonSerialize
或使用注释为某些属性指定它,例如:
public class MyClass {
@JsonSerialize(nullsUsing = NullSerializer.class)
private String property;
}