Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Customizing behaviour on incorrect type in JSON #21

Open
omartijn opened this issue Jan 15, 2024 · 2 comments
Open

Customizing behaviour on incorrect type in JSON #21

omartijn opened this issue Jan 15, 2024 · 2 comments

Comments

@omartijn
Copy link

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
Copy link
Author

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
Copy link
Member

eao197 commented Jan 15, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants