Skip to content

Commit 47344b2

Browse files
authored
Merge pull request #242 from mthl/java-time-instant
Write `java.time.Instant` objects
2 parents f9a61e7 + e83f749 commit 47344b2

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

src/cheshire/generate_seq.clj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
(java.util Date Map List Set SimpleTimeZone UUID)
77
(java.sql Timestamp)
88
(java.text SimpleDateFormat)
9+
(java.time Instant)
910
(clojure.lang IPersistentCollection Keyword Symbol)))
1011

1112
(definline write-start-object [^JsonGenerator jg wholeness]
@@ -127,4 +128,8 @@
127128
(g/i? Timestamp obj) (let [sdf (doto (SimpleDateFormat. date-format)
128129
(.setTimeZone (SimpleTimeZone. 0 "UTC")))]
129130
(g/write-string ^JsonGenerator jg (.format sdf obj)))
131+
(g/i? Instant obj) (let [sdf (doto (SimpleDateFormat. date-format)
132+
(.setTimeZone (SimpleTimeZone. 0 "UTC")))
133+
d (Date/from obj)]
134+
(g/write-string ^JsonGenerator jg (.format sdf d)))
130135
:else (g/fail obj jg ex))))

test/cheshire/test/core.clj

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,19 @@
211211
(is (= {"foo" "1970-01-01-0004"}
212212
(json/decode (json/encode {:foo (Instant/ofEpochSecond (long 0))}
213213
{:date-format "yyyy-MM-dd-uuuu"})))
214-
"use [[java.text.SimpleDateFormat]] format rules"))
214+
"use [[java.text.SimpleDateFormat]] format rules")
215+
216+
(is (= {"foo" "1970-01-01T00:00:00Z"}
217+
(json/decode
218+
(str (json/with-writer [(StringWriter.) nil]
219+
(json/write {:foo (Instant/ofEpochSecond (long 0))}))))))
220+
221+
(is (= {"foo" "1970-01-01"}
222+
(json/decode
223+
(str
224+
(json/with-writer [(StringWriter.) {:date-format "yyyy-MM-dd"}]
225+
(json/write {:foo (Instant/ofEpochSecond (long 0))})))))
226+
"write with given date format"))
215227

216228
(deftest test-uuid
217229
(let [id (UUID/randomUUID)

0 commit comments

Comments
 (0)