- nlohmann源码仓库:https://github.com/nlohmann/json
- 使用方式:将其nlohmann文件夹加入,包含其头文件json.hpp即可
- demo
#include <iostream>
#include "nlohmann/json.hpp"
#include <vector>
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;
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
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}});
}
// 将JSON对象转换为字符串
std::string jsonString = jsonData.dump(4); // 4-space indentation for pretty formatting
// 打印生成的JSON字符串
std::cout << "Generated JSON:" << std::endl;
std::cout << jsonString << std::endl;
// 反序列化JSON字符串到结构体
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;
}
文章来源地址https://www.toymoban.com/news/detail-692032.html
文章来源:https://www.toymoban.com/news/detail-692032.html
到了这里,关于使用nlohmann json库进行序列化与反序列化的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!