杰克逊空列表到空数组序列化 [英] Jackson null list to empty array serialization
问题描述
我想将空列表序列化为空数组.
I want to serialize null List to empty array.
所以给定了:
class MyBean { List values; }
给定一个实例,该实例的值为null,则应将其序列化为:
And given an instance with null for values, it should be serialized to:
{ "values": [] }
我希望这是所有类中所有列表的全局行为.我不想为类添加任何注释或特定处理.
I want this to be global behaviour for all Lists in all classes. I do not want to add any annotations or specific handling for classes.
我已经阅读了所有发现的相关问题,无法提出任何可行的解决方案.似乎我尝试注册List类的所有自定义序列化程序都没有启动.
I have read all related questions I found, and could not come up with anything that works. Seems any custom serializer I try to register for List class is not kicking in.
如果您正在处理项目,请告诉我您是如何做到的.
If you have this working on your project, let me know how did you manage to do that.
推荐答案
在这种情况下,您需要自定义JacksonAnnotationIntrospector
类.序列化null
-s,默认情况下,Jackson
使用com.fasterxml.jackson.databind.ser.std.NullSerializer
类.您可以扩展默认的内省者类并覆盖findNullSerializer
.
In cases like this you need to customize JacksonAnnotationIntrospector
class. Te serialize null
-s, by default, Jackson
uses com.fasterxml.jackson.databind.ser.std.NullSerializer
class. You can extend default introspector class and override findNullSerializer
.
请参见以下示例:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new EmptyArrayJacksonAnnotationIntrospector());
mapper.writeValue(System.out, new ListWrapper());
}
}
class EmptyArrayJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {
@Override
public Object findNullSerializer(Annotated a) {
if (List.class.isAssignableFrom(a.getRawType())) {
return ArrayNullSerializer.INSTANCE;
}
return super.findNullSerializer(a);
}
}
final class ArrayNullSerializer extends StdSerializer<Object> {
public static final ArrayNullSerializer INSTANCE = new ArrayNullSerializer();
protected ArrayNullSerializer() {
super(Object.class);
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartArray();
gen.writeEndArray();
}
}
class ListWrapper {
private List values;
public List getValues() {
return values;
}
public void setValues(List values) {
this.values = values;
}
}
上面的代码显示:
{"values":[]}
这篇关于杰克逊空列表到空数组序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!