问题
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