import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.boot.jackson.JsonComponent;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import static java.util.regex.Pattern.compile;
/**
* 日期字符串转日期类型
* jack json消息转换器全局配置
*/
@JsonComponent
public class JsonDateDeserializer extends JsonDeserializer<Date> {
private String[] patterns = {
"yyyy-MM-dd"
, "yyyy-MM-dd HH:mm:ss"
, "yyyy-MM-dd HH:mm:ss.SSS"
, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
};
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
String dateAsString = jsonParser.getText();
if (dateAsString == null || "".equals(dateAsString) || dateAsString.length() < 1) {
return null;
}
//时间的毫秒数转日期
if (compile("[0-9]*").matcher(dateAsString).matches()) {
return new Date(Long.valueOf(dateAsString));
}
Date parseDate = null;
try {
parseDate = DateUtils.parseDate(dateAsString, patterns);
} catch (ParseException e) {
throw new IllegalArgumentException(e.getCause());
}
return parseDate;
}
}