解決json日期格式問題
1.json默認輸出時間格式
@RequestMapping("/json3")
public String json3() throws JsonProcessingException {ObjectMapper mapper = new ObjectMapper();//創建時間一個對象,java.util.DateDate date = new Date();//將我們的對象解析成為json格式String str = mapper.writeValueAsString(date);return str;
}
運行結果 :
- 默認日期格式會變成一個數字,是1970年1月1日到當前日期的毫秒數!
- Jackson 默認是會把時間轉成timestamps形式
2.解決方案:取消timestamps形式 , 自定義時間格式
@RequestMapping("/json4")
public String json4() throws JsonProcessingException {ObjectMapper mapper = new ObjectMapper();//不使用時間戳的方式mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);//自定義日期格式對象SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//指定日期格式mapper.setDateFormat(sdf);Date date = new Date();String str = mapper.writeValueAsString(date);return str;
}
運行結果 : 成功的輸出了時間!
3.抽取為工具類
如果要經常使用的話,這樣是比較麻煩的,我們可以將這些代碼封裝到一個工具類中
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;public class JsonUtils {public static String getJson(Object object) {return getJson(object,"yyyy-MM-dd HH:mm:ss");}public static String getJson(Object object,String dateFormat) {ObjectMapper mapper = new ObjectMapper();//不使用時間差的方式mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);//自定義日期格式對象SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);//指定日期格式mapper.setDateFormat(sdf);try {return mapper.writeValueAsString(object);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}
}
我們使用工具類,代碼就更加簡潔了!
@RequestMapping("/json5")
public String json5() throws JsonProcessingException {Date date = new Date();String json = JsonUtils.getJson(date);return json;
}