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

女生的网名这么多〃 提交于 2021-01-29 10:22:45

问题


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!


回答1:


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)))) 


来源:https://stackoverflow.com/questions/60331109/how-to-print-edn-output-in-json-format-using-cheshire-custom-encoder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!