json_dto
json_dto copied to clipboard
Customizing behaviour on incorrect type in JSON
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.
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?
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.