Map flat struct to nested object #421
Answered
by
stephenberry
azais-corentin
asked this question in
Q&A
-
Hello, Flat c++ struct: struct Test
{
int64_t id;
double latitude;
double longitude;
}; Nested json object: {
"id": 12,
"coordinates": {
"latitude": 1.23456789,
"longitude": 9.87654321
}
} I have been playing with object mapping and object types but I was not able to achieve the desired result. |
Beta Was this translation helpful? Give feedback.
Answered by
stephenberry
Sep 1, 2023
Replies: 1 comment 2 replies
-
This will be simpler when reading is added for
struct test_mapping_t
{
int64_t id;
double latitude;
double longitude;
};
struct coordinates_t
{
double* latitude;
double* longitude;
};
template <>
struct glz::meta<coordinates_t>
{
using T = coordinates_t;
static constexpr auto value = object("latitude", &T::latitude, "longitude", &T::longitude);
};
template <>
struct glz::meta<test_mapping_t>
{
using T = test_mapping_t;
static constexpr auto value = object("id", &T::id, "coordinates", [](auto& self) { return coordinates_t{&self.latitude, &self.longitude}; });
};
suite mapping_struct = [] {
"mapping_struct"_test = [] {
test_mapping_t obj{};
std::string s = R"({
"id": 12,
"coordinates": {
"latitude": 1.23456789,
"longitude": 9.87654321
}
})";
expect(!glz::read_json(obj, s));
expect(obj.id == 12);
expect(obj.latitude == 1.23456789);
expect(obj.longitude == 9.87654321);
};
}; This will be easier in the future, but for now you have to build intermediate structures. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
stephenberry
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will be simpler when reading is added for
glz::obj
, but for now here is a solution: