#include
#include "nlohmann/json.hpp"
#include
using json = nlohmann::json;
struct Address
{
std::string street;
std::string city;
};
struct Person
{
std::string name;
int age;
bool isStudent;
std::vector<int> grades;
Address address;
std::vector<Address> addresses;
};
int main()
{
Person person;
person.name = "John";
person.age = 30;
person.isStudent = false;
person.grades = {90, 85, 92};
person.address = {"123 Main St", "Anytown"};
person.addresses = {{"456 Elm St", "Somewhere"}, {"789 Oak St", "Nowhere"}};
json jsonData = {
{"name", person.name},
{"age", person.age},
{"isStudent", person.isStudent},
{"grades", person.grades},
{"address", {{"street", person.address.street}, {"city", person.address.city}}},
{"addresses", json::array()}};
jsonData["age"] = 20;
for (const auto &addr : person.addresses)
{
jsonData["addresses"].push_back({{"street", addr.street},
{"city", addr.city}});
}
std::string jsonString = jsonData.dump(4);
std::cout << "Generated JSON:" << std::endl;
std::cout << jsonString << std::endl;
Person parsedPerson;
json parsedData = json::parse(jsonString);
parsedPerson.name = parsedData["name"];
parsedPerson.age = parsedData["age"];
parsedPerson.isStudent = parsedData["isStudent"];
std::vector<int> parsedGrades = parsedData["grades"].get<std::vector<int>>();
parsedPerson.address.street = parsedData["address"]["street"];
parsedPerson.address.city = parsedData["address"]["city"];
parsedPerson.addresses.clear();
for (const auto &addr : parsedData["addresses"])
{
Address parsedAddr;
parsedAddr.street = addr["street"];
parsedAddr.city = addr["city"];
parsedPerson.addresses.push_back(parsedAddr);
}
std::cout << "Name: " << parsedPerson.name << std::endl;
std::cout << "Age: " << parsedPerson.age << std::endl;
std::cout << "Is Student: " << parsedPerson.isStudent << std::endl;
std::cout << "Grades: ";
for (int grade : parsedPerson.grades)
{
std::cout << grade << " ";
}
std::cout << std::endl;
std::cout << "Address: Street: " << parsedPerson.address.street << ", City: " << parsedPerson.address.city << std::endl;
std::cout << "Addresses:" << std::endl;
for (const auto &addr : parsedPerson.addresses)
{
std::cout << "Street: " << addr.street << ", City: " << addr.city << std::endl;
}
return 0;
}
- 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