如何在@RestController参数中使用@XmlJavaTypeAdapter?

时间:2016-07-19 12:55:37

标签: java spring spring-mvc spring-data spring-web

我有以下restcontroller,并希望以thedate=2016-08-08格式查询控制器。

它应自动转换为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;
}

结果:

  

&#39; thedate&#39;:无法转换类型[java.lang.String]的属性值   要求属性的类型[java.time.LocalDate]&#39; thedate&#39 ;;嵌套   例外是   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&#39; 2016-08-08&#39 ;;嵌套异常是   java.time.format.DateTimeParseException:Text&#39; 2016-08-08&#39;不能   在索引2解析

1 个答案:

答案 0 :(得分:0)

我不知道它为什么不起作用,但我使用弹簧注释解决了它:

var BPromise = require('bluebird');

var uploadDone = new BPromise(function (resolve, reject) {

    // your image upload

});

uploadDone.then(function (result) {

   // upload complete here

}, function (error) {
   console.log("Error: ", error);
});