Jackson Mapper序列化空对象而不是null [英] Jackson Mapper serialize empty object instead of null
问题描述
假设我有课程Foo
public class Foo {
private Bar bar;
}
和Bar
public class Bar {
private String fizz;
private String bang;
}
编辑:为了澄清我不拥有 Foo
和 Bar
并且不能改变这些类。
EDIT: For clarification I do not own Foo
and Bar
and cannot alter these classes.
如果我想序列化一个Foo类型的空对象,它的成员是Bar类型,将返回null。
If I want to serialize an empty object of type Foo, it's member, which is of type Bar, will be returned as null.
String json = objectMapper.writeValueAsString(new Foo()); // "{"bar" : null}"
我有什么方法可以得到对象映射器序列化一个空的Bar对象,而不必实例化一个新的Bar实例,然后将其添加到一个新的Foo实例?
Is there any way I can get the object mapper to serialize an empty Bar object without having to instantiate a new instance of Bar and then adding it to a new instance of Foo?
String json = objectMapper.writeValueAsString(new Foo()) // "{bar": {"fizz" : null, "bang" : null } }"
推荐答案
您可以创建一个自定义序列化程序来序列化Foo对象。然后在您的自定义FooSerializer实现中,您可以检查空值和将其序列化为默认的Bar实例。请参阅 https:// spin。 atomicobject.com/2016/07/01/custom-serializer-jackson/ 或 http ://www.baeldung.com/jackson-custom-serialization ,了解如何创建自定义序列的一些示例lizers。
You could create a custom serializer for serializing Foo objects. Then in your custom FooSerializer implementation, you could check for a null bar value and serialize it as a default Bar instance. See https://spin.atomicobject.com/2016/07/01/custom-serializer-jackson/ or http://www.baeldung.com/jackson-custom-serialization for some examples of how to create custom serializers.
这篇关于Jackson Mapper序列化空对象而不是null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!