我从Spring Boot App调用App服务,使用jackson-jsr-310作为能够使用LocalDateTime
的maven依赖项
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = this.createHeaders();
ResponseEntity<String> response;
response = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
BusinessPartner test = mapper.readValue(response.getBody(), BusinessPartner.class);
我的问题是在最后一行,代码产生了这个错误:
java.time.format.DateTimeParseException:未能在索引0处分析文本'/Date(591321600000)/‘
在response.getBody()
中生成的JSON如下所示:
{
"d":{
...
"Address":{...},
"FirstName":"asd",
"LastName":"asd",
"BirthDate":"\/Date(591321600000)\/",
}
}
在我的模型类中,我有以下成员:
@JsonProperty("BirthDate")
private LocalDateTime birthDate;
所以,在这里搜索了一下后,我发现这个/Date(...)/
似乎是微软专有的here格式,默认情况下,Jackson不能将其反序列化为对象。
有些问题建议创建一个自定义的SimpleDateFormat
并将其应用于对象映射器,这是我试图做到的,但是我认为我错过了mapper.setDateFormat(new SimpleDateFormat("..."));
的正确语法
我试过了,比如mapper.setDateFormat(new SimpleDateFormat("/Date(S)/"));
或者在最后甚至是mapper.setDateFormat(new SimpleDateFormat("SSSSSSSSSSSS)"));
但这似乎也不起作用,所以我现在没有想法,希望这里的一些人能帮助我。
edit 1:
进一步研究,似乎有一种方法是为杰克逊编写一个定制的DateDeSerializer
。所以我试了一下:
@Component
public class JsonDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private DateTimeFormatter formatter;
private JsonDateTimeDeserializer() {
this(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
public JsonDateTimeDeserializer(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
if (parser.hasTokenId(JsonTokenId.ID_STRING)) {
String unixEpochString = parser.getText().trim();
unixEpochString = unixEpochString.replaceAll("[^\\d.]", "");
long unixTime = Long.valueOf(unixEpochString);
if (unixEpochString.length() == 0) {
return null;
}
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(unixTime), ZoneId.systemDefault());
localDateTime.format(formatter);
return localDateTime;
}
return null;
}
}
它实际上返回了我想要的内容,在模型中使用
@JsonDeserialize(using = JsonDateTimeDeserializer.class)
但并不完全是这样:这段代码返回一个值:1988-09-27T01:00
。但是在第三方系统中,xml值是1988-09-27T00:00:00
。
很明显,这里的ZoneId:
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(unixTime), ZoneId.systemDefault());
是问题所在,除了错误的日期格式。
那么这里有没有人能帮我把time
-part转换成总是使用0,并让我的日期格式正确呢?那就太好了!
https://stackoverflow.com/questions/44432789
复制相似问题