Stiffstream / json_dto

A small header-only library for converting data between json representation and c++ structs
BSD 3-Clause "New" or "Revised" License
149 stars 18 forks source link

Customizing behaviour on incorrect type in JSON #21

Open omartijn opened 10 months ago

omartijn commented 10 months ago

I'd like to be able to customize what happens when deserializing a value that is defined in the JSON, but that has the wrong type. As an example, the following JSON:

{"x":"abc"}

and deserializing like this:

struct X {
    int x;

    template <typename io_type>
    void json_io(io_type& io)
    {
        json_dto::optional("x", x, 0);
    }
};

This leads to an exception because we are expecting a number, but are getting a string instead. It'd be nice if we could set a policy that we use the default value in that case.

omartijn commented 10 months ago

Thinking about this a bit, we'd probably have to ensure that we have the Reader_Writer parameter for all (read|write)_json_value functions. It's now there for some (i.e. std::optional and std::vector) but not for others (i.e. std::string).

Then we can define a member function to invoke if the type is incorrect, which in the default implementation would throw. Do you think that makes sense?

eao197 commented 10 months ago

Hi!

My first thought is to use a special Reader_Writer implementation that checks the type of a value in rapidjson::Value and then reads it or uses a default value.