2016-07-19 49 views
0

我有以下的restcontroller,並想用thedate=2016-08-08格式查詢控制器。如何在@RestController參數中使用@XmlJavaTypeAdapter?

它應該被自動轉換爲java.time.LocalDate。 但我的XmlAdapter不起作用。爲什麼?

import java.time.LocalDate; 
import java.time.format.DateTimeFormatter; 
import javax.xml.bind.annotation.adapters.XmlAdapter; 

public class LocalDateAdapter extends XmlAdapter<String, LocalDate> { 

    @Override 
    public LocalDate unmarshal(String v) throws Exception { 
     return LocalDate.parse(v, DateTimeFormatter.ISO_LOCAL_DATE); 
    } 

    @Override 
    public String marshal(LocalDate v) throws Exception { 
     return DateTimeFormatter.ISO_LOCAL_DATE.format(date); 
    } 
} 

@RestController 
public class MyServlet { 
    @RequestMapping(value = "/", method = RequestMethod.GET) 
    private String test(RestParams p) { 

    } 
} 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class RestParams { 
     @Valid 
     @NotNull 
     @XmlElement(required = true, nillable = false) 
     @XmlJavaTypeAdapter(value = LocalDateAdapter.class) 
     private LocalDate thedate; 
} 

結果:

'thedate':無法類型的屬性值轉換[java.lang.String中] 所需類型[java.time.LocalDate用於屬性 'thedate';嵌套0​​例外是 org.springframework.core.convert.ConversionFailedException:未能 從類型[java.lang.String中]轉換成鍵入[@ javax.validation.Valid @ javax.validation.constraints.NotNull @javax。 xml.bind.annotation.XmlElement @ javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter java.time.LocalDate] for value'2016-08-08';嵌套的例外是 java.time.format.DateTimeParseException:文本「2016年8月8日」無法 在指數解析2

+0

您是否嘗試調試到'marshal'和'unmarshal'來查看它們是否被調用? –

+0

是的,我的適配器似乎根本沒有被調用。就好像它沒有註冊。但爲什麼? – membersound

回答

0

我不知道爲什麼它不工作,但我解決它使用彈簧註釋:

@org.springframework.format.annotation.DateTimeFormat.DateTimeFormat(iso = ISO.DATE) 
    private java.time.LocalDate thedate; 
相關問題