metosin / jsonista

Clojure library for fast JSON encoding and decoding.
https://cljdoc.org/d/metosin/jsonista
Eclipse Public License 2.0
422 stars 30 forks source link

Deserizlize Joda Datetime #76

Closed tomer8888 closed 4 months ago

tomer8888 commented 5 months ago

Following the README example, how can I deserialize back to clj-time?


;; [com.fasterxml.jackson.datatype/jackson-datatype-joda "2.9.5"]
(import '[com.fasterxml.jackson.datatype.joda JodaModule])
(import '[org.joda.time LocalDate])

(def mapper
  (j/object-mapper
    {:modules [(JodaModule.)]}))

(j/write-value-as-string (LocalDate. 0) mapper)
; "\"1970-01-01\""

(j/read-value *1 mapper) 
; => "1970-01-01"
ikitommi commented 4 months ago

Hi. The parser doesn't know that a string should be parsed into some object. You should companion jsonista with something like malli to define a schema for the data and apply a type-transformation on top of the normal JSON parsing.

let date = new Date();
// Tue Jul 09 2024 16:52:37 GMT+0300 (Eastern European Summer Time)

JSON.stringify(date)
// '"2024-07-09T13:52:37.434Z"'

JSON.parse(JSON.stringify(date))
// '2024-07-09T13:52:37.434Z'
ikitommi commented 4 months ago

with malli, using plain Dates (transformers supported out-of-the-box):

(j/write-value-as-string {:date (java.util.Date.)})
; => "{\"date\":\"2024-07-09T13:59:00Z\"}"

(j/read-value *1 j/keyword-keys-object-mapper)
; => {:date "2024-07-09T13:59:00Z"}

(m/decode [:map [:date inst?]] *1 mt/json-transformer)
; => {:date #inst"2024-07-09T13:59:00.000-00:00"}
tomer8888 commented 3 months ago

@ikitommi thanks but i'm looking for a more robust solution based on the object mapper (tagged json maybe?)

ikitommi commented 3 months ago

By robust, you mean self-contained? Parsing strings that look like dates always into dates is not robust, convenient maybe. You can look for Tagged JSON if you don't want to go the malli way. Hope you'll find a good enough solution for this.