java - Jackson 2.6.3 反序列化避免文字 null 添加到集合中

标签 java json jackson deserialization

我正在尝试使用 Jackson 2.6.3 反序列化 json 上下文。我的 json 内容中有空文字,如下所示。我试图避免将其添加到反序列化集合中。请参阅下面的输出。我在映射器上尝试了各种配置选项。但是我无法避免集合中的空对象。欢迎任何解决问题的指示。

我在 stackoverflow 中看到了许多类似的问题,如下所示,但所有这些问题都与自定义反序列化类中的各个属性有关,而不是与集合中的元素有关。

How to deserialize JSON null to a NullNode instead of Java null?

JSON 内容(Data.txt)

{
  "myList": [
  {
     "type": "1"
  },
  {
     "type": "2"
  },
  null
  ]
}

RootObject.java

@JsonInclude(Include.NON_NULL)
public class RootObject {

private List<Types> myList;

public List<Types> getMyList() {
    return myList;
}

public void setMyList(List<Types> myList) {
    this.myList = myList;
}

public String toString(){
    return new ReflectionToStringBuilder(this).toString();
}
}

类型.java

@JsonInclude(Include.NON_NULL)
public class Types {

private String type;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String toString(){
    return new ReflectionToStringBuilder(this).toString();
}
}

jackson 测试仪

public class JacksonTester2 {

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getSerializationConfig().withSerializationInclusion(Include.NON_EMPTY);
        mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        RootObject rootObject = null;
        try {
            rootObject = mapper.readValue(new File("Data.txt"), RootObject.class);
        } catch (Exception e) {
            e.printStackTrace();
        } 
        System.out.println(rootObject);
    }
    }

输出

RootObject@1a74681a[myList=[Types@ace10d9[type=1], Types@5eb41c19[type=2], null]]

最佳答案

我从以下帖子中得到了灵感

Jackson: Ignore whitespace in empty @XmlWrapperElement collection

这是针对上述问题的解决方案

public class NullCollectionHandler extends SimpleModule {
    private static class CustomizedCollectionDeserialiser extends CollectionDeserializer {

        public CustomizedCollectionDeserialiser(CollectionDeserializer src) {
            super(src);
        }

        private static final long serialVersionUID = 1L;

        @Override
        public Collection<Object> deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            Collection<Object> oldCol = super.deserialize(jp, ctxt);
            Collection<Object> newCol = new ArrayList<Object>();
            if(CollectionUtils.isNotEmpty(oldCol)){
                for(Object obj : oldCol){
                    if(obj != null)
                    newCol.add(obj);
                }
            }
            return newCol;
        }

        @Override
        public CollectionDeserializer createContextual(DeserializationContext ctxt,
                BeanProperty property) throws JsonMappingException {
            return new CustomizedCollectionDeserialiser(super.createContextual(ctxt, property));
        }
    }

    private static final long serialVersionUID = 1L;

    @Override
    public void setupModule(SetupContext context) {
        super.setupModule(context);
        context.addBeanDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyCollectionDeserializer(
                    DeserializationConfig config, CollectionType type,
                    BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
                if (deserializer instanceof CollectionDeserializer) {
                    return new CustomizedCollectionDeserialiser(
                        (CollectionDeserializer) deserializer);
                } else {
                    return super.modifyCollectionDeserializer(config, type, beanDesc,
                        deserializer);
                }
            }
        });
    }
}

关于java - Jackson 2.6.3 反序列化避免文字 null 添加到集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553553/

相关文章:

jsonp - 在 Jersey Rest 中使用 @Consume 和 GET 请求

java - 使用从文本字段获取的输入修改从数据库获取的字符串

java - IntelliJ-java : Cannot find JDK '1.8'

java - 如何将一种 JSON 模式映射到另一种模式?

java - 对象转换为 json 时变为 null

java - JSON 解析错误 : Cannot deserialize instance of. 。超过 START_ARRAY token

java - spring-data-cassandra 未找到 UserDefinedType

java - 使用 Android Volley 解析 JSON URL - JsonObjectRequest

jquery - JSON 数据的格式可能不正确

java - 重命名所有 JSON 键 - Java - Jackson - spring boot