cheshire icon indicating copy to clipboard operation
cheshire copied to clipboard

Support some kind of fallback encoder

Open rafaeldff opened this issue 5 years ago • 3 comments

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.

rafaeldff avatar Jan 13 '20 21:01 rafaeldff

I have precisely the same use case / issue.

camdez avatar Feb 22 '20 18:02 camdez

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

stathissideris avatar Mar 23 '20 15:03 stathissideris

Same for me! Has anyone found a descent workaround?

viebel avatar Nov 22 '20 15:11 viebel