2015-04-02 55 views
1

我開發了一個使用春季啓動和春季啓動啓動程序仇恨的休息服務。而且我正面臨着定製ObjectMapper的問題。代碼低於對於相同的:自定義的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: 

但我需要「法案」到位「billList」的。這是因爲ObjectMapper沒有得到定製。我是否缺少任何配置,請幫助我解決這個問題。提前致謝。

+0

'Bill'上的@JsonRootName怎麼可能對屬性名'billList'產生影響? – zeroflagL 2015-04-02 18:48:34

+0

我有同樣的問題,你有沒有解決這個問題? – 2017-01-25 09:26:08

+0

稍微深入一下,通過Spring源代碼和一些Google搜索,我發現這個問題描述了這個問題https://github.com/spring-projects/spring-hateoas/issues/333 – 2017-01-25 10:07:40

回答

0

我正在使用spring-boot 1.5 RC1。如果刪除了@EnableHypermediaSupport註釋,只要您在類路徑中有java時間模塊,spring-boot應該爲您配置帶有ISO 8601日期的spring-hateoas。

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

無論如何,這對我有效。

如果你想進一步自定義配置,在這個問題的http://github.com/spring-projects/spring-hateoas/issues/333

0

根看到了解決方案 - 從Spring MVC的默認ObjectMapper使用,而不是一個由作者進行配置。 這是因爲@EnableWebMvc。從Spring Boot guide

報價通常你會添加@EnableWebMvc了Spring MVC的應用程序,但是當它看到的 類路徑彈簧webmvc春 開機自動添加它。

但是,如果你說的話,Spring MVC將創建它自己的一組MessageConverters,並且不會使用你的ObjectMapper。

PS即使我這麼晚發佈這個答案,可能會幫助別人。