SPRING REST:以JSON格式从响应中删除空对象

时间:2015-10-15 10:29:15

标签: java json spring rest

我没有选择spring.xml,所以我选择了带注释的方法。

我在包中有以下REST接口:com.dpk.cm.impl.ecommerce.rest 和com.dpk.cm.impl.ecommerce.rest.services中的实现

我创建了一个spring配置类:但似乎我仍然在我的JSON响应中看到空对象。

以下是我的代码:

@Configuration
@ComponentScan(basePackages = "com.dpk.cm.impl.ecommerce.rest")
@EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        final ObjectMapper objectMapper = new ObjectMapper();
       // objectMapper.setSerializationInclusion(Inclusion.NON_EMPTY);
        objectMapper.setSerializationInclusion(Include.NON_EMPTY);    
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }
}

如何从JSON Reponse对象中删除空对象。

2 个答案:

答案 0 :(得分:0)

我有类似的要求,但是虽然我在spring boot上使用CXF框架,但是spring boot正在创建覆盖配置的ObjectMapper。因此我手动创建了ObjectMapper,如下所示。

@Bean(name = "objectMapper")
    public ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(
                SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
                true);
        mapper.setSerializationInclusion(Include.NON_NULL);
        return mapper;
    }

答案 1 :(得分:0)

You can create your custom serializer where you can add a condition on serialization of the object.

Model

@JsonSerialize(using = IgnoreEmptyPersonSerializer.class)
public class Person {

    private String name;
    private String address;

    public Person(String name, String address){
        this.name = name;
        this.address = address;
    }
    ...
    //setters and getters
    ...
}

Custom Serializer

public class IgnoreEmptyPersonSerializer extends JsonSerializer<Person> {

    @Override
    public void serialize(Person value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        String name = value.getName();
        String address = value.getAddress();

        //Dont serialize it if it is empty
        if((name == null || name.trim().equals("")) &&
                (address == null || address.trim().equals(""))){
            return;
        }

        jgen.writeStartObject();
        jgen.writeFieldName("name");
        jgen.writeString(value.getName());
        jgen.writeFieldName("address");
        jgen.writeString(value.getAddress());
        jgen.writeEndObject();

    }
}