java - Spring 根据请求自动转换 LocalDate

标签 java spring

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')

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

最佳答案

添加一个配置类,将JavaTime模块添加到jackson:

@Configuration
public class SampleApplication {

  @Autowired
  private ObjectMapper objectMapper;

  @PostConstruct
  public void createObjectMapper() {
    objectMapper.registerModule(new JavaTimeModule());
  }
}

关于java - Spring 根据请求自动转换 LocalDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58182099/

相关文章:

java.net.SocketException : Connection reset

java - Android Studio newProject卡在gradle项目信息中

java - 将 UTC 日期转换为不同时区的日期

java - 如何将 spring bean 注入(inject) Validator(hibernate)

java - Tic Tac Toe Java GUI 设置游戏 field

java - 如何使用尊重自定义注释的 jackson 执行自定义 JSON 反序列化?

java - 如何从加载中排除bean?

spring - 将 Spring MBean 导出到 Tomcat 的 MBeanServer 实例

Spring Boot 1.3.0 Websocket 与 Spring Security DefaultSimpUserRegistry getSession NullPointerException

java - Spring安全-httpbasic不工作: What am i doing wrong?