将未初始化的收集字段序列化为空

将未初始化的收集字段序列化为空

本文介绍了杰克逊:将未初始化的收集字段序列化为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字段或属性的POJO,其中包含对象的集合,如下所示:

I have a POJO with a field or property, containing collection of objects, something like this:

public class Box {

    public List<Items> items;

}

默认情况下,items的值为空,并且我不想使用空列表进行初始化.

By default, value of items is null, and I do not want to initialize it with empty list.

现在,如果我尝试用Jackson对其进行序列化,则会得到NullPointerException.有没有一种简单的方法可以使Jackson不中断该值并将其序列化为空集合:[ ]?

Now, if I try to serialize it with Jackson, I get NullPointerException. Is there a simple way to make Jackson not break on such value and serialize it as an empty collection: [ ]?

注意.此类仅是一个简化示例.实际上,有数百个类和许多名称不同的字段,它们有时在代码中的某些地方有时设置为null,从而破坏了运行时的序列化.

Note. This class is just a simplified example. In reality, there are a hundred of classes and a number of fields with different names in each of them, which are occasionally set to null sometimes somewhere in the code, breaking serialization in runtime.

推荐答案

如果不想更改POJO类的协定,请考虑定义扩展 JsonSerializer< T>的自定义Jackson序列化器/反序列化器的可能性. ; JsonDeserializer< T> .例如:

If you do not want to change the contract of your POJO class, think about the possibility to define custom Jackson serializer / deserializer which extend JsonSerializer<T> and JsonDeserializer<T> respectively. E.g.:

 public class CountryDeserializer extends JsonDeserializer<CountryCode> {
     @Override
     public CountryCode deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
         return CountryCode.getByCode(jp.getText());
     }
 }

然后

 @JsonDeserialize(using=CountryDeserializer.class)
 private CountryCode country;

您可以检查字段是否为空,并在两个方向(序列化/反序列化)上采取相应措施.

You can check whether your field is null and act accordingly, in both directions (serialization / deserialization).

这篇关于杰克逊:将未初始化的收集字段序列化为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:59