-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathflatten.cpp
90 lines (81 loc) · 2.16 KB
/
flatten.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <serdepp/serde.hpp>
#include <serdepp/adaptor/fmt.hpp>
#include <serdepp/adaptor/nlohmann_json.hpp>
#include <serdepp/adaptor/rapidjson.hpp>
struct Object {
DERIVE_SERDE(Object,
(&Self::radius, "radius")
(&Self::width, "width")
(&Self::height, "height"))
std::optional<int> radius;
std::optional<int> width;
std::optional<int> height;
};
struct Test {
DERIVE_SERDE(Test,
(&Self::type, "type")
[attributes(flatten)]
(&Self::object, "object"))
std::string type;
Object object;
};
using namespace rapidjson;
int main() {
nlohmann::json jflat = R"([
{"type": "circle", "radius": 5},
{"type": "rectangle", "width": 6, "height": 5}
])"_json;
nlohmann::json j = R"([
{"type": "circle", "object": {"radius" : 5}},
{"type": "rectangle", "object": {"width": 6, "height": 5}}
])"_json;
auto j_flatten = serde::deserialize<std::vector<Test>>(jflat);
auto j_none = serde::deserialize<std::vector<Test>>(j);
fmt::print("{}\n",serde::serialize<nlohmann::json>(j_flatten).dump());
fmt::print("{}\n",serde::serialize<nlohmann::json>(j_none).dump());
auto print = [](auto& doc) {
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
std::cout << "doc:" << buffer.GetString() << std::endl;
};
auto doc_flat = serde::serialize<rapidjson::Document>(j_flatten);
print(doc_flat);
auto doc_none = serde::serialize<rapidjson::Document>(j_none);
print(doc_none);
fmt::print("{}\n",serde::deserialize<std::vector<Test>>(doc_flat));
fmt::print("{}\n",serde::deserialize<std::vector<Test>>(doc_none));
}
//OUTPUT
/*
[
{
"object": {
"radius": 5
},
"type": "circle"
},
{
"object": {
"height": 5,
"width": 6
},
"type": "rectangle"
}
]
[
{
"object": {
"radius": 5
},
"type": "circle"
},
{
"object": {
"height": 5,
"width": 6
},
"type": "rectangle"
}
]
*/