Reputation: 11
I have list of json objects,one of the fields is date. The problem is that the dates are written in diffrent ways in json.
most of them looks like:
"publishedDate": "2005-01-28"
"publishedDate": "2011-08-29"
"publishedDate": "2016-04-19"
But some of them is like:
"publishedDate": "1998-11"
"publishedDate": "2001-01"
My java object field to which i want to parse
private Date publishedDate;
I got this error:
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))
Upvotes: 0
Views: 1169
Reputation: 38710
You need to write custom deserialiser for a Date
and in both cases properly convert to expected date. Below you can find simple example how to do that:
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 +
'}';
}
}
Above program for JSON
payload:
[
{
"publishedDate": "2005-01-28"
},
{
"publishedDate": "1998-11"
}
]
Prints:
[Item{publishedDate=Fri Jan 28 00:00:00 CET 2005}, Item{publishedDate=Sun Nov 01 00:00:00 CET 1998}]
Upvotes: 1