从Jackson序列化中的数组中删除空的JSON对象 [英] Remove empty JSON objects from an array in Jackson serialization

查看:309
本文介绍了从Jackson序列化中的数组中删除空的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java Pojo类中有一个列表.该列表包含一些MyChildPojo对象,这些对象不为null,但可以具有带有null值的属性.示例:

I have a List in a Java Pojo class. That list contains some MyChildPojo objects which are not null but can have properties with null values. Example:

MyChildPojo obj1 = new MyChildPojo();
MyChildPojo obj2 = new MyChildPojo();

我在MyChildPojo类上添加了@JsonInclude(JsonInclude.Include.NON_EMPTY),因此在序列化对象时不会添加null属性. 现在,我对List对象的最终序列化输出是:

I have added @JsonInclude(JsonInclude.Include.NON_EMPTY) on my MyChildPojo class so null properties will not be added while serializing the object. Now my final serialized output for the List object is:

[
  {}, {}
]

在这种情况下,我想删除完整的List对象.我尝试通过在List对象上添加@JsonInclude(JsonInclude.Include.NON_EMPTY)@JsonInclude(value = Include.NON_EMPTY, content = Include.NON_EMPTY),但是仍然获得相同的输出.

I want to remove the complete List object in this case. I have tried by adding @JsonInclude(JsonInclude.Include.NON_EMPTY) and @JsonInclude(value = Include.NON_EMPTY, content = Include.NON_EMPTY) on the List object but still getting the same output.

我只能在我的情况下使用注释.有什么可行的方法吗?

I can only use annotation in my case. Is there any possible way to do this?

推荐答案

您可以使用带有自定义过滤器的注释来执行此操作.在整个MyChildPojo对象只是外壳的情况下,您可以在自定义过滤器中完全省略list属性.

You can use annotations with custom filter to do this. In the custom filter you can omit the list property altogether when the whole set of MyChildPojo objects are just shell.

使用

注释MyChildPojo

@JsonInclude(value = JsonInclude.Include.NON_EMPTY, valueFilter = EmptyListFilter.class)
public class MyChildPojo {
...
}

并定义EmptyListFilter类似于以下内容

public class EmptyListFilter {
    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof List)) {return false;}
        Optional<Object> result = ((List)obj).stream().filter(
                eachObj -> Arrays.asList(eachObj.getClass().getDeclaredFields()).stream().filter(eachField -> {
                    try {
                        eachField.setAccessible(true);
                        if ( eachField.get(eachObj)  != null && !eachField.get(eachObj).toString().isEmpty()) {
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return false;
                }).count() > 0).findAny();
       return  !result.isPresent();
    }
}

示例对Java:8

   compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.11.0'
   compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'

这篇关于从Jackson序列化中的数组中删除空的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆