日期直接轉json
@RequestMapping(value = "/json4",produces = "application/json;charset=utf-8") //String 的轉換格式 produces = "text/html;charset=utf-8"
@ResponseBody
public String json4 () throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Date date = new Date();
return mapper.writeValueAsString(date);
}
配上展示圖,可以看到回傳的是一個時間戳,下面我們就來**

改進后:
@RequestMapping(value = "/json4",produces = "application/json;charset=utf-8") //String 的轉換格式 produces = "text/html;charset=utf-8"
@ResponseBody
public String json4 () throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//為了不回傳時間戳,所以我們選擇關閉它
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//自定義日期格式問題
final SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS");
//設定mapper的指定的日期格式
mapper.setDateFormat(sdf);
Date date = new Date();
return mapper.writeValueAsString(date);
}

我發了兩篇關于json可以看到代碼重復過多,且次次拋出例外,所以我將在下一篇博客來進行封裝成工具類!
uj5u.com熱心網友回復:
有不足之處,望不吝指出轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/11254.html
標籤:Web 開發
下一篇:Filter [springSecurityFilterChain]: could not be initialized
