我有 json 对象列表,其中一个字段是日期。问题是日期在 json 中以不同的方式写入。
大多数看起来像:
"publishedDate": "2005-01-28"
"publishedDate": "2011-08-29"
"publishedDate": "2016-04-19"
但其中一些是这样的:
"publishedDate": "1998-11"
"publishedDate": "2001-01"
我想要解析的 java 对象字段
private Date publishedDate;
我收到此错误:
Cannot deserialize value of type `java.util.Date` from String "2001-01": not a valid representation (error: Failed to parse Date value '2001-01': Cannot parse date "2001-01": while it seems to fit format 'yyyy-MM-dd', parsing fails (leniency? null))
最佳答案
您需要为Date
编写自定义反序列化器,并在这两种情况下正确转换为预期日期。您可以在下面找到如何执行此操作的简单示例:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Item>> typeReference = new TypeReference<List<Item>>() {
};
List<Item> readValue = mapper.readValue(jsonFile, typeReference);
System.out.println(readValue);
}
}
class DifferentFormatsDateJsonDeserializer extends JsonDeserializer<Date> {
private DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private DateTimeFormatter yearMonthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
try {
if (value.length() == 7) {
YearMonth yearMonth = YearMonth.parse(value, yearMonthFormatter);
return convertToDateViaInstant(yearMonth.atDay(1));
} else {
LocalDate localDate = LocalDate.parse(value, localDateFormatter);
return convertToDateViaInstant(localDate);
}
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public Date convertToDateViaInstant(LocalDate dateToConvert) {
return Date.from(dateToConvert.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
}
}
class Item {
@JsonDeserialize(using = DifferentFormatsDateJsonDeserializer.class)
private Date publishedDate;
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
@Override
public String toString() {
return "Item{" +
"publishedDate=" + publishedDate +
'}';
}
}
以上 JSON
有效负载的程序:
[
{
"publishedDate": "2005-01-28"
},
{
"publishedDate": "1998-11"
}
]
打印:
[Item{publishedDate=Fri Jan 28 00:00:00 CET 2005}, Item{publishedDate=Sun Nov 01 00:00:00 CET 1998}]
关于java - 如何反序列化不同格式的日期: YYYY-MM-DD and YYYY-MM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099794/