boostorg / json

A C++11 library for parsing and serializing JSON to and from a DOM container in memory.
https://boost.org/libs/json
Boost Software License 1.0
429 stars 93 forks source link

Direct parsing of custom types #1044

Open sdebionne opened 1 day ago

sdebionne commented 1 day ago

About direct parsing, the documentation states that:

The drawback of this approach is that fully custom type representations are not supported, only the library-provided conversions are.

I wonder where this limitation stands?

I have a described struct with an std::chrono::duration member. While I have the proper tag_invoke overloads, since there is no built-in conversion support for std::chrono, I can't use parse_into. Is that correct?

Would it be possible to add new customization points to allow direct parsing of custom types?

Any chance to add a conversion category for date /time / duration (if that make sense)?

grisumbras commented 12 hours ago

Direct parsing is implemented using a special event handler that is a tree of dedicated subhandlers for components of the target value, and works by descending to the first subhandlers that accepts a parsing event. The implementation relies on cooperation of parent and child subhandlers.

In order to allow users to add support for their types we would have to make this system a public API and document how all that works. I'm not sure it's a very good idea, because writing those subhandlers is very tricky.

I have an alternative idea, which I'm still not sure I could pull off, but we'll see. The idea is to have representation "proxies". You define a trait that your type is supposed to be represented as some other type, and converter/parser will create an object of that type and will do conversion/parsing into that object instead.

This would provide a significant degree of customisation opportunities, like representing a chrono::duration as a number of ticks, or a chrono::time_point as an ISO 8601 string.