Reputation: 2480
i am using JsonDeserializer to format my Date as below:
public class CustomDateMappingDeserialize extends JsonDeserializer<Date>{
@Override
public Date deserialize(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = paramJsonParser.getText();
try {
Date formattedDate= format.parse(date);
return formattedDate;
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
but the problem is i have to define the Format fixed here and i have many different date formats.
Can we do something like this:
@JsonDeserialize(using = CustomDateMappingDeserialize.class, format ="yyy-dd-mm")
public void setDate(Date date) {
this.date = date;
}
Instead of defining it in Custom class ?
Any help/pointers would be highly appreciated.
Upvotes: 0
Views: 3533
Reputation: 4948
For a previous requirement of similar nature i had used multi parser options as documented here.
Following similar lines , the following custom class is an example
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class CustomDeserializer extends JsonDeserializer<Date> {
private static final String[] DATE_FORMATS = new String[] { "MMM dd, yyyy HH:mm:ss", "MMM dd, yyyy" };
@Override
public Date deserialize(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext)
throws IOException, JsonProcessingException {
// TODO Auto-generated method stub
if (paramJsonParser == null || "".equals(paramJsonParser.getText()))
return null;
String date = paramJsonParser.getText();
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(date);
} catch (ParseException e) {
}
}
return null;
}
}
Edit :
You can also use additional libraries as outlined by suggestion here using MultiDateTimeParsers.
Upvotes: 1