Different serialization/deserialization rules #119
-
Hi! Right now, we are only able to write the object to json...
Like I said, this works when writing to json, but where and if even possible can I provide a definition on how to read in the json? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
I don't think this is documented yet but you can fully specialize or partial template specialize from_json and to_json for your custom type. An example of this can be seen in the Eigen matrix stuff here https://github.com/stephenberry/glaze/blob/main/include/glaze/ext/eigen.hpp I think @stephenberry was planning on providing some more details/background on this. |
Beta Was this translation helpful? Give feedback.
-
To explain @mwalcott3 answer further: This kind of custom reading/writing is best handled by implementing your own Here is a very simplified example of your problem: // custom type handling
struct date
{
uint64_t data;
std::string human_readable;
};
template <>
struct glz::meta<date>
{
using T = date;
static constexpr auto value = object("date", &T::human_readable);
};
namespace glz::detail
{
template <>
struct from_json<date>
{
template <auto Opts>
static void op(date& value, auto&&... args)
{
read<json>::op<Opts>(value.human_readable, args...);
value.data = std::stoi(value.human_readable);
}
};
template <>
struct to_json<date>
{
template <auto Opts>
static void op(date& value, auto&&... args) noexcept
{
value.human_readable = std::to_string(value.data);
write<json>::op<Opts>(value.human_readable, args...);
}
};
}
suite date_test = []
{
"date"_test = [] {
date d{};
d.data = 55;
std::string s{};
glz::write_json(d, s);
expect(s == R"("55")");
d.data = 0;
glz::read_json(d, s);
expect(d.data == 55);
};
}; |
Beta Was this translation helpful? Give feedback.
-
This works really well, but I have a question. Is it possible to for example if std::stoi throws, to fail the deserialization and report it in the error code? Something like:
|
Beta Was this translation helpful? Give feedback.
@klemenpeganc
To explain @mwalcott3 answer further:
This kind of custom reading/writing is best handled by implementing your own
from_json
andto_json
specializations within the glz::detail namespace.Here is a very simplified example of your problem: