3.9之后新增了 2个宏 可以实现 结构体和json的快速转换
1.结构体序列化json
1.1 3.9
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"// 定义用户结构体
struct User
{std::string name; // 用户名int age; // 年龄std::vector<std::string> hobbies; // 爱好列表NLOHMANN_DEFINE_TYPE_INTRUSIVE(User, name, age, hobbies)
};// 定义数据结构体
struct Data
{User user; // 用户信息bool active; // 活跃状态NLOHMANN_DEFINE_TYPE_INTRUSIVE(Data, user, active)
};int main()
{// 创建一个 Data 对象Data data;data.user.name = "Alice";data.user.age = 30;data.user.hobbies = {"Reading", "Traveling", "Swimming"};data.active = true;// 序列化 Data 对象到 JSONnlohmann::json jsonData = data; //仅一行代码完成序列化std::cout << "Serialized JSON: " << jsonData.dump(4) << std::endl;return 0;
}
1.2 3.9 之前
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"// 定义用户结构体
struct User
{std::string name; // 用户名int age; // 年龄std::vector<std::string> hobbies; // 爱好列表friend void to_json(nlohmann::json &nlohmann_json_j, const User &nlohmann_json_t){nlohmann_json_j["name1"] = nlohmann_json_t.name;nlohmann_json_j["age1"] = nlohmann_json_t.age;nlohmann_json_j["hobbies1"] = nlohmann_json_t.hobbies;}
};// 定义数据结构体
struct Data
{User user; // 用户信息bool active; // 活跃状态friend void to_json(nlohmann::json &nlohmann_json_j, const Data &nlohmann_json_t){nlohmann_json_j["user1"] = nlohmann_json_t.user;nlohmann_json_j["active1"] = nlohmann_json_t.active;}
};int main()
{// 创建一个 Data 对象Data data;data.user.name = "Alice";data.user.age = 30;data.user.hobbies = {"Reading", "Traveling", "Swimming"};data.active = true;// 序列化 Data 对象到 JSONnlohmann::json jsonData = data;std::cout << "Serialized JSON: " << jsonData.dump(4) << std::endl;return 0;
}
2.json反序列化到结构体
2.1 3.9
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"// 定义用户结构体
struct User
{std::string name; // 用户名int age; // 年龄std::vector<std::string> hobbies; // 爱好列表// 使用 NLOHMANN_DEFINE_TYPE_INTRUSIVE 宏来定义序列化和反序列化方法NLOHMANN_DEFINE_TYPE_INTRUSIVE(User, name, age, hobbies)
};// 定义数据结构体
struct Data
{User user; // 用户信息bool active; // 活跃状态// 使用 NLOHMANN_DEFINE_TYPE_INTRUSIVE 宏来定义序列化和反序列化方法NLOHMANN_DEFINE_TYPE_INTRUSIVE(Data, user, active)
};int main()
{// 创建一个 Data 对象std::string jsonstr = R"(
{"active": true,"user": {"age": 30,"hobbies": ["Reading","Traveling","Swimming"],"name": "Alice"}
})";std::cout << jsonstr << std::endl;nlohmann::json jsonData = nlohmann::json::parse(jsonstr);Data deserializedData;// 反序列化 JSON 到 Data 对象try{deserializedData = jsonData.get<Data>();}catch (std::exception &e){std::cout << "[" << __LINE__ << "]" << e.what() << std::endl;return false;}// 打印反序列化后的数据std::cout << "Deserialized Data:" << std::endl;std::cout << "Name: " << deserializedData.user.name << std::endl;std::cout << "Age: " << deserializedData.user.age << std::endl;std::cout << "Hobbies: ";for (const auto &hobby : deserializedData.user.hobbies){std::cout << hobby << " ";}std::cout << std::endl;std::cout << "Active: " << std::boolalpha << deserializedData.active << std::endl;return 0;
}
2.2 3.9之前
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"// 定义用户结构体
struct User
{std::string name; // 用户名int age; // 年龄std::vector<std::string> hobbies; // 爱好列表friend void from_json(const nlohmann::json &nlohmann_json_j, User &nlohmann_json_t){nlohmann_json_j.at("name1").get_to(nlohmann_json_t.name);nlohmann_json_j.at("age1").get_to(nlohmann_json_t.age);nlohmann_json_j.at("hobbies1").get_to(nlohmann_json_t.hobbies);}
};// 定义数据结构体
struct Data
{User user; // 用户信息bool active; // 活跃状态friend void from_json(const nlohmann::json &nlohmann_json_j, Data &nlohmann_json_t){nlohmann_json_j.at("user1").get_to(nlohmann_json_t.user);nlohmann_json_j.at("active1").get_to(nlohmann_json_t.active);}
};int main()
{// 创建一个 Data 对象std::string jsonstr = R"(
{"active1": true,"user1": {"age1": 30,"hobbies1": ["Reading","Traveling","Swimming"],"name1": "Alice"}
})";std::cout << jsonstr << std::endl;nlohmann::json jsonData = nlohmann::json::parse(jsonstr);Data deserializedData;// 反序列化 JSON 到 Data 对象try{deserializedData = jsonData.get<Data>();}catch (std::exception &e){std::cout << "[" << __LINE__ << "]" << e.what() << std::endl;return false;}// 打印反序列化后的数据std::cout << "Deserialized Data:" << std::endl;std::cout << "Name: " << deserializedData.user.name << std::endl;std::cout << "Age: " << deserializedData.user.age << std::endl;std::cout << "Hobbies: ";for (const auto &hobby : deserializedData.user.hobbies){std::cout << hobby << " ";}std::cout << std::endl;std::cout << "Active: " << std::boolalpha << deserializedData.active << std::endl;return 0;
}
3.nlohmann的传统用法 序列化和 反序列化
#include <iostream>
#include "json.hpp"
#include <stdexcept>using json = nlohmann::json;int main()
{std::string jsonstr = R"( {"active": true,"user": {"age": 30,"hobbies": ["Reading","Traveling","Swimming"],"name": "Alice"}})";try{json j = json::parse(jsonstr);bool active = false;if (j.contains("active") && j["active"].is_boolean()){active = j["active"];}else{std::cerr << "Warning: 'active' key is missing or not a boolean, using default value: false" << std::endl;}std::string name = "Unknown";if (j.contains("user") && j["user"].contains("name") && j["user"]["name"].is_string()){name = j["user"]["name"];}else{std::cerr << "Warning: 'user.name' key is missing or not a string, using default value: Unknown" << std::endl;}int age = 0;if (j.contains("user") && j["user"].contains("age") && j["user"]["age"].is_number()){age = j["user"]["age"];}else{std::cerr << "Warning: 'user.age' key is missing or not a number, using default value: 0" << std::endl;}std::vector<std::string> hobbies;if (j.contains("user") && j["user"].contains("hobbies") && j["user"]["hobbies"].is_array()){for (const auto &hobby : j["user"]["hobbies"]){if (hobby.is_string()){hobbies.push_back(hobby);}}}else{std::cerr << "Warning: 'user.hobbies' key is missing or not an array, using default value: empty" << std::endl;}std::cout << "Active: " << active << std::endl;std::cout << "Name: " << name << std::endl;std::cout << "Age: " << age << std::endl;std::cout << "Hobbies: ";for (const auto &hobby : hobbies){std::cout << hobby << " ";}std::cout << std::endl;}catch (const std::exception &e){std::cerr << "Error: " << e.what() << std::endl;return 1;}// 组装新的 JSON 报文std::vector<std::string> hobbies;hobbies.push_back("sing");hobbies.push_back("dance");hobbies.push_back("rap");json newJson;newJson["active"] = false;newJson["user"]["name"] = "Blice";newJson["user"]["age"] = 18;newJson["user"]["hobbies"] = hobbies;std::string newJsonStr = newJson.dump(4);std::cout << "New JSON String:\n"<< newJsonStr << std::endl;return 0;
}
4.json特殊字段 空对象 空数组 空字符串 空值
#include <iostream>
#include "json.hpp"int main()
{// 生成空对象nlohmann::json emptyObject = nlohmann::json::object();std::cout << "Empty Object: " << emptyObject << std::endl;// 生成空数组nlohmann::json emptyArray = nlohmann::json::array();std::cout << "Empty Array: " << emptyArray << std::endl;// 生成空字符串nlohmann::json emptyString = "";std::cout << "Empty String: " << emptyString << std::endl;// 生成空值nlohmann::json nullValue = nullptr;std::cout << "Null Value: " << nullValue << std::endl;return 0;
}