Welcome! Please see the About page for a little more info on how this works.

0 votes
in Libs by

Is there a generic way to (de)serialize arrays using transit?

I find myself in this situation:

(require '[cognitect.transit :as transit])

(def array-write-handler (transit/write-handler "pod.babashka.sql/array" vec))

(def array-type (class (into-array Object [])))

(defn write-transit [v]
  (let [baos (java.io.ByteArrayOutputStream.)]
    (transit/write (transit/writer baos :json {:handlers {array-type array-write-handler}}) v)
    (.toString baos "utf-8")))

(prn (write-transit (into-array Object ["foo"]))) ;; works
(prn (write-transit (into-array String ["foo"]))) ;; ERROR

and it looks like you have to encode serialization explicitly for every type, which can be error prone and tedious. Can I use some sort of fallback handler before transit decides it cannot encode a certain type of object? In this fallback I could check if the object is an array using .isArray?

The way I currently work around this is using walk/postwalk and make some custom representation, but this seems to defeat the purpose of transit.

2 Answers

0 votes
by
edited by
 
Best answer

Transit added support for :default-handler:

https://github.com/cognitect/transit-clj/commit/972759aed878d354fbd65de3e4525345955e86b4

That might solve the issue as you get a change to inspect the value and do something appropriate like serializing or throwing.

Gist demo: https://gist.github.com/borkdude/0a99a4f413b509315d54e1c68f861fad

0 votes
by

For transit stuff, you can just file issues on https://github.com/cognitect/transit-clj/issues rather than here.

by
Well, this was rather a question than an issue, but I'll file it over there then.
by
edited by
EDIT: comment obsolete
...