2

当尝试通过 RestTemplate 发布到 Spring-Data-Rest Web 服务时,我的域对象的 JSON 表示正在转换为不在 HAL 表示中的完整 JSON 对象。我在这里的假设是我需要将 Jackson2HalModule 注册为反序列化器,但考虑到我将它注册到 objectMapper 时我不确定该怎么做。在 web 服务上调用 GET 时,序列化工作正常,但不适用于 POST/PUT:

请求 outputBuffer 字段:

{
  "id" : 1,
  "name" : "Name",
  "description" : "",
  "childObject" : {
    "id" : 1,
    "name" : "test"
  }
} 

休息模板配置:

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.setDateFormat(new ISO8601DateFormat());
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.registerModule(new Jackson2HalModule());
    return objectMapper;
}

public void configureMessageConverters(
        List<HttpMessageConverter<?>> messageConverters) {
    MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
    jsonMessageConverter.setObjectMapper(objectMapper());
    jsonMessageConverter.setSupportedMediaTypes(MediaType
            .parseMediaTypes("application/hal+json,application/json"));
    messageConverters.add(jsonMessageConverter);
}

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    configureMessageConverters(messageConverters);
    restTemplate.setMessageConverters(messageConverters);
    return restTemplate;
}

请求标头:

  HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

调用方法:

ResponseEntity<DomainObject> responseEntity =
    restTemplate.exchange(this.getBaseUri() + resolveResource(), HttpMethod.POST, new HttpEntity(domainObject,createHttpHeaders(tenantId)), DomainObject.class);
4

1 回答 1

0

我认为您不应该注册自己的 ObjectMapper。Spring 为您创建它并注册所有需要的模块。所以我会尝试删除你的 ObjectMapper bean。

如果您需要自定义 ObjectMapper,您可以使用 Jackson2ObjectMapperBuilder。有关更多详细信息,请参阅文档 - http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-jackson-objectmapper

@Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return Jackson2ObjectMapperBuilder //
                .json() //
                .locale(ENGLISH) //
                .timeZone("UTC") //
                .indentOutput(true) //
                .serializationInclusion(NON_NULL) //
                .featuresToDisable(WRITE_DATES_AS_TIMESTAMPS, FAIL_ON_UNKNOWN_PROPERTIES) //
                ;
    }

我也会让 spring 处理消息转换器:

因此,当您创建 RestTemplate 时让 spring 注入它们 - 就像这样:

@Bean
public RestTemplate restTemplate(List<HttpMessageConverter<?>> messageConverters) {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(messageConverters);
    return restTemplate;
}
于 2015-09-24T14:03:22.470 回答