gpt4 book ai didi

java - 如何更新 RestTemplate 以正确映射 Java 日期?

转载 作者:行者123 更新时间:2023-11-30 05:46:53 27 4
gpt4 key购买 nike

我遇到一个问题,我的 RestTemplate.postForEntity(url, restRequest, RepoResponse.class) 调用失败,因为它无法反序列化表单的日期:

  • 2019-02-01T12:00:00.000-0500

因为时区中缺少冒号。

基于this answer ,看起来我想更改 RestTemplateObjectMapper 的日期格式。

我在这里尝试了一个解决方案: https://stackoverflow.com/a/38286322/14250

这给了我以下代码:

restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS[XXX][X]");
objectMapper.setDateFormat(format);

MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setPrettyPrint(false);
messageConverter.setObjectMapper(objectMapper);
restTemplate.getMessageConverters().removeIf(m->m.getClass().getName().equals(MappingJackson2HttpMessageConverter.class.getName()));
restTemplate.getMessageConverters().add(messageConverter);

不幸的是我收到以下错误

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.OffsetDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-02-13T12:33:19.179-0500')

有没有简单的方法让 RestTemplate 支持上述日期时间格式?

最佳答案

当您使用 java.time.* 类和 Jackson 时,最好从注册来自 jackson-datatype-jsr310JavaTimeModule 开始。模块。

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.time.OffsetDateTime;

public class JsonApp {

public static void main(String[] args) throws Exception {
JavaTimeModule javaTimeModule = new JavaTimeModule();

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(javaTimeModule);

String json = "{\"now\":\"2019-02-01T12:01:01.001-0500\"}";
System.out.println(mapper.readValue(json, Time.class));
}
}

class Time {

@JsonFormat(pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSX")
private OffsetDateTime now = OffsetDateTime.now();

public OffsetDateTime getNow() {
return now;
}

public void setNow(OffsetDateTime now) {
this.now = now;
}

@Override
public String toString() {
return "PrintObject{" +
"now=" + now +
'}';
}
}

上面的代码打印:

PrintObject{now=2019-02-01T17:01:01.001Z}

关于java - 如何更新 RestTemplate 以正确映射 Java 日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54676382/

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