Transit

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (95 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 EDN | TOC | Appendix 4 Database Access 👉

Transit has feature parity with EDN but has some slight quirks because it’s more optimized and it’s more commonly used across different environments. Most notably, the default tags are different from EDN.

Here’s an example of a reader/writer pair for a LocalDate type in Clojure taken from luminus-transit.[103]

​ ​;; In Clojure​
​ (​require​ '[cognitect.transit :as transit])
​ (import '[java.time LocalDate]
​ '[java.io ByteArrayInputStream ByteArrayOutputStream]
​ '[java.time.format DateTimeFormatter])

​ (​def​ read-handlers {​"LocalDate"​
​ (​transit/read-handler​
​ #(​java.time.LocalDate/parse​ %
​ (​DateTimeFormatter/ofPattern​ ​"yyyy-MM-dd"​)))})
​ (​def​ write-handlers
​ {java.time.LocalDate
​ (​transit/write-handler​
​ (constantly ​"LocalDate"​)
​ #(​.format​ % (​DateTimeFormatter/ofPattern​ ​"yyyy-MM-dd"​)))})

​ (​def​ out (​ByteArrayOutputStream.​ 4096))

​ (​transit/write​ (​transit/writer​ out :json {:handlers write-handlers})
​ (​LocalDate/of​ 2020 12 31))

​ (println (​.toString​ out))
​ ​;; => ["~#LocalDate", "2020-12-31"]​

​ (println
​ (​transit/read​
​ (​transit/reader​ (​ByteArrayInputStream.​ (​.toByteArray​ out))
​ :json
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.