如何避免我的REST JSON响应中的空对象?

时间:2019-06-28 05:41:32

标签: json spring-boot jackson

我在JSON响应中得到了类似的信息(我在SpringBoot中具有REST实现):

"estimatedDeliveryTimeWindow":{  
  "window":{}
}

我已经设置了自定义HTTPMessageCOnverters并配置了objectMapper,如下所示:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

还尝试使用以下代码删除默认转换器:

@Bean
public HttpMessageConverters converters() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        jsonConverter.setObjectMapper(objectMapper);
        return new HttpMessageConverters(false, Arrays.asList(jsonConverter));
}

似乎没有任何效果。我仍然在对象中看到空对象。这些对象是嵌套有基本类型和自定义对象的复杂对象。我还能尝试什么?

2 个答案:

答案 0 :(得分:1)

请在课程文件之前添加 @JsonInclude(Include.NON_NULL)

@JsonInclude(Include.NON_NULL)
public class MobileLoginVO {

    private String otpDetailsId;

    public String getOtpDetailsId() {
        return otpDetailsId;
    }

    public void setOtpDetailsId(String otpDetailsId) {
        this.otpDetailsId = otpDetailsId;
    }

}

答案 1 :(得分:0)

您需要以某种方式通知以使用您的消息转换器。

这应该可以完成工作:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    public MappingJackson2HttpMessageConverter messageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        jsonConverter.setObjectMapper(objectMapper);

        return jsonConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(messageConverter());
    }
}