在Spring RestControllers中使用Field Formatter

时间:2016-02-16 07:52:14

标签: spring spring-mvc spring-restcontroller

我尝试让一个RestController使用我的自定义格式化程序用于java.time.Duration,但我不知道为什么不成功。我有一个简单的Order实体,一个OrderController和一个DurationFormatter,它应该用于将Order的Duration类型字段转换为Strings。 Formatter在Configuration类中注册了FormattingConversionServiceFactoryBean。这是代码:

public class Order {
    @Getter
    @Setter
    private String id;

    @Getter
    @Setter
    @NotNull
    private String customerId;

    @Getter
    @Setter
    private ZonedDateTime validFrom;

    @Getter
    @Setter
    private ZonedDateTime validTo;

    @Getter
    @Setter
    private Duration maxDuration;

    @Getter
    @Setter
    private Duration actDuration;
}

@RestController
@RequestMapping("order")
public class OrderController {

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> createOrder(@RequestBody @Valid Order order) {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/" + order.getId()).build().toUri());
        return new ResponseEntity<>(null, headers, HttpStatus.CREATED);
    }

    @RequestMapping(method = RequestMethod.GET)
    public Order getExample() {
        Order order = new Order();
        order.setMaxDuration(Duration.ofHours(10));
        return order;
    }
}

public class DurationFormatter implements Formatter<Duration>{

    @Override
    public String print(Duration duration, Locale locale) {
        return new Long(duration.toHours()).toString();
    }

    @Override
    public Duration parse(String text, Locale locale) throws ParseException {
        return Duration.ofHours(Long.parseLong(text));
    }

}

@Configuration
public class AppConfig {
    @Bean
    public FormattingConversionServiceFactoryBean getFormattingConversionServiceFactory() {
        FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
        Set<Formatter<?>> formatters = new HashSet<>();
        formatters.add(new DurationFormatter());
        factory.setFormatters(formatters);
        return factory;
    }
}

当我尝试发布订单时,这是我得到的错误:

  

at [来源:java.io.PushbackInputStream@595e3818; line:4,专栏:   30](通过参考链:   com.sap.sptutorial.rest.Order [ “maxDuration”]);嵌套异常是   com.fasterxml.jackson.databind.JsonMappingException:不能   实例化类型[simple type,class java.time.Duration]的值   字符串值('67');没有单字符串构造函数/工厂方法

有人可以建议我使用格式化程序的正确方法吗?

1 个答案:

答案 0 :(得分:1)

格式化程序与JSON反序列化无关。在您的情况下,这是Jackson的任务。应该将以下依赖项添加到pom.xml以获得对新Java 8类型的支持。

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