4
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
objectMapper.setDateFormat(new ISO8601DateFormat());
不錯,但是這忽略了毫秒,我怎麼能在沒有使用非線程安全的SimpleDateFormatter
的日期得到它們?ISO8601在json中使用Jackson的毫秒數
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
objectMapper.setDateFormat(new ISO8601DateFormat());
不錯,但是這忽略了毫秒,我怎麼能在沒有使用非線程安全的SimpleDateFormatter
的日期得到它們?ISO8601在json中使用Jackson的毫秒數
ISO8601DateFormat.format
電話ISO8601Utils.format(date)
,進而調用format(date, false, TIMEZONE_Z)
- 在false
參數告訴傑克遜不包括毫秒。
似乎有沒有辦法來配置這個類也沒有設置任何參數,但好在它可以擴展:
ObjectMapper objectMapper = new ObjectMapper();
ISO8601DateFormat dateFormat = new ISO8601WithMillisFormat();
objectMapper.setDateFormat(dateFormat);
:
public class ISO8601WithMillisFormat extends ISO8601DateFormat {
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true); // "true" to include milliseconds
toAppendTo.append(value);
return toAppendTo;
}
}
然後我們就可以在對象映射器使用這個新類
我用new Date()
進行了測試,結果爲2017-07-24T12:14:26.817Z
(以毫秒爲單位)。