項目環境:
Spring MVC 4 jackson
問題描述:
在Controller中需要返回json數據時,有的業務需要返回年月日格式,有的業務需要返回年月日時分秒格式,而我配置了全局的日期處理方式爲年月日(因爲大量業務只需要年月日)。
解決方案:
在需要年月日時分秒的字段上加上註解@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 即可
擴展:
- @JsonIgnoreProperties
此註解是類註解,作用是json序列化時將java bean中的一些屬性忽略掉,序列化和反序列化都受影響。
- @JsonIgnore
此註解用於屬性或者方法上(最好是屬性上),作用和上面的@JsonIgnoreProperties一樣。
- @JsonFormat
此註解用於屬性或者方法上(最好是屬性上),可以方便的把Date類型直接轉化爲我們想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
- @JsonSerialize
此註解用於屬性或者getter方法上,用於在序列化時嵌入我們自定義的代碼,比如序列化一個double時在其後面限制兩位小數點。
public class CustomDoubleSerialize extends JsonSerializer<Double> {
private DecimalFormat df = new DecimalFormat("##.00");
@Override
public void serialize(Double value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeString(df.format(value));
}
}
- @JsonDeserialize
此註解用於屬性或者setter方法上,用於在反序列化時可以嵌入我們自定義的代碼,類似於上面的@JsonSerialize
public class CustomDateDeserialize extends JsonDeserializer<Date> {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
Date date = null;
try {
date = sdf.parse(jp.getText());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
文章參考:點擊打開鏈接