-
Notifications
You must be signed in to change notification settings - Fork 0
/
joc_sample.cpp
128 lines (115 loc) · 2.73 KB
/
joc_sample.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "JsonObjectConverter.hpp"
#include <list>
using namespace joc;
enum ContactType {
Family,
Friend,
Work
};
void to_json(nlohmann::json& j, const ContactType& contactType) {
switch (contactType)
{
case ContactType::Family:
j = "Family";
return;
case ContactType::Friend:
j = "Friend";
return;
default:
j = "Work";
}
}
void from_json(const nlohmann::json& j, ContactType& contactType) {
if (j == "Family") {
contactType = ContactType::Family;
} else if (j == "Friend") {
contactType = ContactType::Friend;
} else {
contactType = ContactType::Work;
}
}
struct Contact : public JsonObject
{
Contact() : JsonObject({{"type", type},
{"name", name},
{"address", address},
{"age", age},
{"e-mail", email}
}) {}
ContactType type;
std::string name;
std::string address;
int age;
std::optional<std::string> email;
};
struct ContactBook : public JsonObject
{
ContactBook() : JsonObject({{"owner", owner},
{"contact_list", contactList}
}) {}
std::string owner;
std::list<Contact> contactList;
};
int main(int argc, char **argv)
{
// Build C++ object and output JSON to console
Contact mary;
mary.name = "Mary";
mary.age = 52;
mary.address = "Olof Str. 4";
mary.type = ContactType::Friend;
std::cout << mary.toJson().dump(2) << std::endl;
// Build nlohmann::json object and convert to our C++ object
nlohmann::json peterJson = {{"name", "Peter"},{"address", "Rua das Amendoas 4"}, {"age", 34}, {"type", "Work"}};
Contact peter;
peter.refreshFromJson(peterJson);
std::cout << peter.toJson().dump(2) << std::endl;
// Change Peter age and add an e-mail
peter.age = 30;
peter.email = "[email protected]";
std::cout << peter.toJson().dump(2) << std::endl;
// Build a ContactBook and output JSON to console
ContactBook myContactBook;
myContactBook.owner = "Ricardo";
myContactBook.contactList = {mary, peter};
std::cout << myContactBook.toJson().dump(2) << std::endl;
/* Output:
{
"address": "Olof Str. 4",
"age": 52,
"name": "Mary",
"type": "Friend"
}
{
"address": "Rua das Amendoas 4",
"age": 34,
"name": "Peter",
"type": "Work"
}
{
"address": "Rua das Amendoas 4",
"age": 30,
"e-mail": "[email protected]",
"name": "Peter",
"type": "Work"
}
{
"contact_list": [
{
"address": "Olof Str. 4",
"age": 52,
"name": "Mary",
"type": "Friend"
},
{
"address": "Rua das Amendoas 4",
"age": 30,
"name": "Peter",
"type": "Work"
}
],
"owner": "Ricardo"
}
*/
return 0;
}