【问题标题】:Spring Boot Microservice Jackson JSON serialisation NON NULLSpring Boot 微服务 Jackson JSON 序列化 NON NULL
【发布时间】:2016-04-09 16:41:14
【问题描述】:

我目前正在开发一个 Spring Boot(版本 1.3.1)微服务,它连接到 MongoDB 后端并通过控制器向客户端提供后端数据(例如:Provider 对象)。

该项目有一个扩展 ResourceSupport 的类文件(例如:ProviderResourceSupport)和另一个扩展 ResourceSupportAssembler 类(例如:ProviderAssembler)的类,用于生成指向响应对象的链接。

理想情况下,我的要求是根据需要自定义 JSON 对象,因此使用 @JsonView(点击此链接 - https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring)并在 maven 项目中添加 Spring Jackson 依赖项。

我还在 application.properties 中添加了 spring.jackson.serialization-inclusion=non-null & spring.jackson.serialization.indent_output=true。

对于控制器中的方法之一,响应将为 'ResponseEntity>' ,如果数据不存在,此方法将返回“null”响应。

我在我的实体对象和控制器上添加了@JsonInclude(Include=NON_NULL),但仍然得到“空”响应。

我不希望将“null”作为响应,并请求您帮助我,以防有人遇到类似问题。

【问题讨论】:

  • 如果数据不存在应该返回什么?
  • 嗨,jny,它应该只返回 HTTP 状态代码 404。我可以检查数据,如果它为空,我将状态代码填充为 404。响应状态代码是右侧填充了“404”,但我应该看不到任何数据。相反,我看到的是“空”响应。

标签: json spring serialization jackson


【解决方案1】:

我修复了这个从扩展 Jackson Mapper Bean 的 json 响应中转义的空属性,但我不使用 Spring Boot,快速查看并检查这是否适合您

public class Jackson2ObjectMapperCustom extends Jackson2ObjectMapperFactoryBean {

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();

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

        Hibernate5Module hibernateModule = new Hibernate5Module();
        hibernateModule.disable(Feature.USE_TRANSIENT_ANNOTATION);
        hibernateModule.enable(Feature.FORCE_LAZY_LOADING);
        getObject().registerModules(new JavaTimeModule(), hibernateModule);
        getObject().configure(SerializationFeature.INDENT_OUTPUT, true);
        getObject().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        getObject().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
    }
}

在我的例子中,我使用 Spring Xml 配置

<bean id="objectMapper" class="com.xxx.common.Jackson2ObjectMapperCustom" />

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper"/>
        </bean>
    </mvc:message-converters>       
</mvc:annotation-driven>

【讨论】:

  • 您好,非常感谢您。但是我使用的是 Spring Boot,并且序列化包含将使用 application.properties 文件定义。所以不能使用它,但再次感谢您的帮助。
  • 大家好,它现在可以正常工作,因为我已将响应类型从“ResponseEntity>”更改为“ResponseEntity”并相应地构建响应对象。
猜你喜欢
  • 2018-11-07
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 2021-03-30
  • 2017-10-30
  • 2019-04-03
相关资源
最近更新 更多