首页 > 解决方案 > Spring从请求中自动转换LocalDate

问题描述

Spring(4.3)是否有可能自动将我的自定义日期转换为 LocalDate 格式?

我有一个简单的请求方法(我不知道它是如何真正调用的):ResponseEntity<?> placeOrder(@RequestBody PlaceOrderForm form);

这是我的 PlaceOrderForm:

public class PlaceOrderForm {
    private LocalDate deliveryDate;

    public LocalDate getDeliveryDate() {
        return deliveryDate;
    }

    public void setDeliveryDate(LocalDate deliveryDate) {
        this.deliveryDate = deliveryDate;
    }
}

我读到了一个自定义转换器......我创建了一个:

@Component
public class StringToLocalDateConverter implements Converter<String, LocalDate> {

    @Override
    public LocalDate convert(String source) {
        String format = messageSource.getMessage("text.store.dateformat", null, i18nService.getCurrentLocale());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

        return LocalDate.parse(source, formatter);
    }
}

我还读到我需要告诉 ConversionService,我有一个新的转换器:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list merge="true">
            <bean id="stringToLocalDateConverter" class="de.test.converter.StringToLocalDateConverter" />
        </list>
    </property>
</bean>

但这一切都无济于事,我收到以下错误: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('10.10.2019'); nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('10.10.2019')

有人可以告诉我我做错了什么吗?

标签: javaspring

解决方案


在类 PlaceOrderForm 中使用注释,如下所示,并在使用时@RequestBody PlaceOrderForm form添加默认构造函数

    public class PlaceOrderForm {
        @DateTimeFormat(pattern = "dd.MM.yyyy")
        private LocalDate deliveryDate;

       public PlaceOrderForm(){}

@controller在类中添加以下方法

 @InitBinder
public void initBinder(final WebDataBinder binder) {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

推荐阅读