nlohmann/json 是一个用于处理 JSON 数据的 C++ 库,提供了简单而强大的 JSON 解析和生成功能。以其简洁易用、功能强大而受到广泛欢迎。
简单易用:
与标准库兼容:
支持多种 JSON 数据类型:
可读性和可维护性:
JSON 序列化和反序列化:
异常处理:
地址: https://github.com/nlohmann/json
git clone --branch=v3.11.3 --single-branch --depth=1 https://github.com/nlohmann/json.git
mkdir build
cd build
cmake ..
make
sudo make install
安装在默认路径下/usr/local/include/nlohmann
将nlohmann的头文件包含进项目工程就好了.
创建和操作 JSON 对象
#include
#include
using json = nlohmann::json;
using namespace std;
int main() {
// 创建 JSON 对象
json j = {
{"name", "John Doe"},
{"age", 30},
{"is_student", false},
{"courses", {"Math", "Science"}}
};
// 访问和修改 JSON 对象
cout << "Name: " << j["name"] << endl;
cout << "Age: " << j["age"] << endl;
j["age"] = 31; // 修改年龄
// 输出整个 JSON 对象
cout << j.dump(4) << endl;
return 0;
}
解析 JSON 字符串
#include
#include
using json = nlohmann::json;
using namespace std;
int main() {
string json_str = R"({"name": "Jane Doe", "age": 25, "is_student": true})";
json j = json::parse(json_str);
cout << "Name: " << j["name"] << endl;
cout << "Age: " << j["age"] << endl;
cout << "Is student: " << (j["is_student"] ? "Yes" : "No") << endl;
return 0;
}
从 std::map 创建 JSON 对象
#include
#include
#include
从 JSON 对象创建 std::map
#include
#include
#include
从 std::vector 创建 JSON 数组
#include
#include
#include
using json = nlohmann::json;
using namespace std;
int main() {
// 创建 std::vector
vector numbers = {1, 2, 3, 4, 5};
// 将 std::vector 转换为 JSON 数组
json j = numbers;
// 输出 JSON 数组
cout << j.dump(4) << endl;
return 0;
}
从 JSON 数组创建 std::vector
#include
#include
#include
using json = nlohmann::json;
using namespace std;
int main() {
// 创建 JSON 数组
json j = {1, 2, 3, 4, 5};
// 从 JSON 数组转换为 std::vector
vector numbers = j.get>();
// 输出 std::vector
for (int num : numbers) {
cout << num << " ";
}
cout << endl;
return 0;
}
#include
#include
#include
#include
using json = nlohmann::json;
using namespace std;
int main() {
// 创建嵌套数据结构
map> data = {
{"group1", {1, 2, 3}},
{"group2", {4, 5, 6}}
};
// 将 std::map 和 std::vector 转换为 JSON 对象
json j = data;
// 输出 JSON 对象
cout << j.dump(4) << endl;
// 从 JSON 对象创建 std::map
map> new_data = j.get>>();
// 输出新创建的 std::map
for (const auto& [key, value] : new_data) {
cout << key << ": ";
for (int num : value) {
cout << num << " ";
}
cout << endl;
}
return 0;
}
通过 nlohmann/json,可以很方便地将 STL 容器与 JSON 数据互转。这使得在 C++ 中处理 JSON 数据变得更加自然,允许你轻松地利用 STL 容器的强大功能。
#include
#include
// 需要序列化的类
class Person {
public:
std::string name;
int age;
// 序列化
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Person, name, age)
};
int main() {
// 创建一个 Person 对象
Person person;
person.name = "Alice";
person.age = 30;
// 将 Person 对象序列化为 JSON
nlohmann::json j = person;
std::cout << "Serialized JSON: " << j << std::endl;
// 反序列化 JSON 为 Person 对象
Person deserializedPerson = j.get();
std::cout << "Deserialized Person - Name: " << deserializedPerson.name
<< ", Age: " << deserializedPerson.age << std::endl;
return 0;
}
结束