jsonclojurecheshire

Encode a Clojure byte array to JSON


I need to encode a Clojure byte array to JSON. I have been trying to do this using Cheshire's add-encoder function, like this:

(add-encoder [Ljava.lang.Byte encode-seq)

The problem is the reader always complains about an unmatched delimiter. I'm trying to encode something like the following:

{:bytes #<byte[] [B@9de27c>}

But this always gives me

JsonGenerationException Cannot JSON encode object of class: class [B: [B@9de27c cheshire.generate/generate (generate.clj:147)

So I'm trying to add a custom encoder. Am I even doing this the right way?


Solution

  • While Clojure will resolve literal symbols containing . as the Java class named by the symbol, you can't specify array classes as Clojure literals because the reader interprets the [ as a token signifying the beginning of a vector. As suggested by this thread, the most concise way to get the byte-array class would be:

     (add-encoder (Class/forName "[B") encode-seq)