SpringMVC中返回Json时间字段格式问题
默认的情况下,springmvc中返回的json对象中,如果有一个date日期类型的字段,它将显示为这个日期对应的时间戳,即一长串数字。
为了让其显示为我们指定的日期格式。可以这样:
1.新建一个CustomDateSerializer类,
public class CustomDateSerializer extends JsonSerializer { @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = formatter.format(value); jgen.writeString(formattedDate); } }
2.在要返回的对象的POJO中该日期字段的get方法上使用annotion为:
@JsonSerialize(using = CustomDateSerializer.class) public Date getCreateTime() { return createTime; }