dakrone / cheshire

Clojure JSON and JSON SMILE (binary json format) encoding/decoding
https://github.com/dakrone/cheshire
MIT License
1.49k stars 151 forks source link

Support some kind of fallback encoder #161

Open rafaeldff opened 4 years ago

rafaeldff commented 4 years ago

My use case is to serialize arbitrary clojure data for logging purposes in a library. I cannot guarantee that data will be acceptable by Cheshire (it can include atoms, functions or other objects). On the other hand, it's fine to just include the .toString value as a json string.

I could build on the support for custom encoders, and define an encoder for java.lang.object such as:

(extend-protocol cheshire.generate/JSONable
    Object
    (to-json [this jsonGenerator]
      (.writeString jsonGenerator (str this))))

The issue with this approach is that it changes cheshire's behavior for the entire program, which is not acceptable in a library (no one expects their logging library to change how it serializes http responses, for instance).

If I could pass a fallback encoder function as an option to generate-string, the scope of the extension would be local to the library.

As another alternative, I could build upon https://github.com/dakrone/cheshire/issues/118 and recurse through the data (maybe with postwalk) before sending it out to cheshire, but I worry about the performance impact.

camdez commented 4 years ago

I have precisely the same use case / issue.

stathissideris commented 4 years ago

Same for me! cheshire.generate/generate could support a fallback option!

viebel commented 3 years ago

Same for me! Has anyone found a descent workaround?