-
Notifications
You must be signed in to change notification settings - Fork 24
/
struct_from_string.cpp
95 lines (78 loc) · 1.68 KB
/
struct_from_string.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
91
92
93
94
95
#include "struct_mapping/struct_mapping.h"
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <string>
namespace sm = struct_mapping;
struct Color
{
int value;
bool operator<(const Color& o) const
{
return value < o.value;
}
};
static Color color_from_string(const std::string & value)
{
if (value == "red")
{
return Color{1};
}
else if (value == "blue")
{
return Color{2};
}
return Color{0};
}
static std::string color_to_string(const Color& color)
{
switch (color.value)
{
case 1: return "red";
case 2: return "blue";
default: return "green";
}
}
struct Background
{
Color color;
};
struct Palette
{
Color main_color;
Background background;
std::list<Color> special_colors;
std::set<Color> old_colors;
std::map<std::string, Color> new_colors;
};
int main()
{
sm::MemberString<Color>::set(color_from_string, color_to_string);
sm::reg(&Palette::main_color, "main_color", sm::Default{"red"});
sm::reg(&Palette::background, "background", sm::Required{});
sm::reg(&Palette::special_colors, "special_colors");
sm::reg(&Palette::old_colors, "old_colors");
sm::reg(&Palette::new_colors, "new_colors");
sm::reg(&Background::color, "color");
Palette palette;
std::istringstream json_data(R"json(
{
"background": {
"color": "blue"
},
"special_colors": ["red", "green", "red", "blue"],
"old_colors": ["red", "green", "blue"],
"new_colors": {
"dark": "green",
"light": "red",
"neutral": "blue"
}
}
)json");
sm::map_json_to_struct(palette, json_data);
std::ostringstream out_json_data;
struct_mapping::map_struct_to_json(palette, out_json_data, " ");
std::cout << out_json_data.str() << std::endl;
}