clojureclojure-java-interopedncheshire

How to print EDN output in JSON format using Cheshire custom encoder


I am newbie with Clojure and I am trying to print EDN output to valid JSON format using Cheshire custom encoder for classes defined in java.

My EDN file:
{:xyz #XyzBuilder "testString"}


Clojure code:

(defn getXyz [str]
    (.getXyz (XyzBuilder.) str)
)

(defn custom-readers []
    {'xyz/builder getXyz}
)

(add-encoder com.java.sample.Xyz
             (fn [c jsonGenerator]
               (.writeString jsonGenerator (str c))))

(edn/read-string
                {:readers (custom-readers)}
                (slurp filename)
)

This generates below output:

{"xyz":"Xyz(sampleString=testString)"}

I want to print it in proper JSON format as below. How can I achieve it?

{"xyz":{"sampleString":"testString"}}

Thanks in advance!


Solution

  • If your java object consists mostly of fields try to convert it to clojure map first and then use chechires's encode-map

    (add-encoder com.java.sample.Xyz
             (fn [c jsonGenerator]
               (-> c 
                   clojure.java/from-java        ;; convert java object to clojure map
                   (select-keys [:sampleString]) ;; select only relevant fields
                   (encode-map jsonGenerator))))