使用nlohmann json库进行序列化与反序列化

  • nlohmann源码仓库:https://github.com/nlohmann/json
  • 使用方式:将其nlohmann文件夹加入,包含其头文件json.hpp即可
  • demo
#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;
    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;
}

你可能感兴趣的:(C/C++,json,c++)