【问题标题】:Customised ObjectMapper not working with spring boot hateoas定制的 ObjectMapper 不适用于 spring boot hatoas
【发布时间】:2015-06-07 12:25:59
【问题描述】:

我使用 spring-boot 和 Spring-boot-starter hatoas 开发了一个休息服务。我在自定义 ObjectMapper 时遇到了问题。代码如下:

Application.java

@Configuration
@Import(BillServiceConfig.class)
@EnableAutoConfiguration
@EnableEurekaClient
@ComponentScan({"com.bill"})
@EnableWebMvc
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class Application extends WebMvcConfigurerAdapter{

@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true).dateFormat(new SimpleDateFormat("MM-yyyy-dd"));
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    builder.configure(objectMapper);
    return builder;
}

依赖关系:

dependencies {
compile "org.springframework.boot:spring-boot-starter-hateoas"
compile "org.springframework.boot:spring-boot-starter-ws"
compile "org.springframework.boot:spring-boot-starter-actuator"

Bill.java:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("bills")
public class Bill{

BillController.java:

public ResponseEntity<Resources<Resource<Bill>>> getBills(){

我得到的输出是:

{
_embedded: {
billList: 

但我需要用“bills”代替“billList”。这是因为 ObjectMapper 没有得到定制。我是否缺少任何配置,请帮助我解决这个问题。提前致谢。

【问题讨论】:

  • @JsonRootName 上的Bill 怎么可能对属性名称billList 产生任何影响?
  • 我也遇到了同样的问题,你解决了吗?
  • 更多地挖掘 spring 源代码和一些谷歌搜索,我遇到了这个问题,它描述了github.com/spring-projects/spring-hateoas/issues/333

标签: rest jackson spring-boot spring-hateoas


【解决方案1】:

我正在使用 spring-boot 1.5 RC1。如果您删除 @EnableHypermediaSupport 注释 spring-boot 应该为您配置带有 ISO 8601 日期的 spring-hateoas,只要您在类路径上有 java 时间模块。

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency> 

无论如何这对我有用。

如果您想要进一步的自定义配置,请参阅http://github.com/spring-projects/spring-hateoas/issues/333 的解决方案

【讨论】:

    【解决方案2】:

    这个问题的根源 - 使用 Spring MVC 的默认 ObjectMapper 而不是作者配置的。 这是因为@EnableWebMvc。

    引用Spring Boot guide

    通常你会为 Spring MVC 应用程序添加 @EnableWebMvc,但 Spring Boot 在看到 spring-webmvc 时会自动添加 类路径。

    但是,如果您说的话,Spring MVC 将创建自己的一组 MessageConverters 并且不会使用您的 ObjectMapper。

    PS 即使我这么晚才发布这个答案,它可能会对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-06-06
      • 1970-01-01
      • 2015-04-13
      • 2018-10-18
      • 2017-05-01
      • 2019-10-19
      • 2021-07-27
      • 1970-01-01
      • 2018-07-04
      相关资源
      最近更新 更多