gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:00:13 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com