问题 传入的日期是字符串类型 json 如下
{"promotename":"促销","starttime":"2019-10-01 00:00:01","endtime":"2019-10-31 23:59:59","rpmax":"1","rpmin":"2"}
页面抽取的日期格式如下:
2019-09-30T16:00:00.000+0000
解决方案:
使用 JsonSerialize与 JsonDeserialize 来处理json转换date日期
添加2个类分别继承 JsonDeserializer<Date>和JsonSerializer<Date>
public class DateJsonSerializer extends JsonSerializer<Date> {public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(format.format(date)); } }
public class DateJsonDeserializer extends JsonDeserializer<Date> { public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public Date deserialize(com.fasterxml.jackson.core.JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, com.fasterxml.jackson.core.JsonProcessingException { try { if(jsonParser!=null&&StringUtils.isNotEmpty(jsonParser.getText())){ return format.parse(jsonParser.getText()); }else { return null; } } catch(Exception e) { System.out.println(e.getMessage()); throw new RuntimeException(e); } } }
在实体类的日期上使用注解:
@JsonDeserialize(using= DateJsonDeserializer.class)
@JsonSerialize(using= DateJsonSerializer.class)
privateDate time;
网友评论