nlohmann::json 容器数据转json举例
时间: 2025-04-20 13:22:22 浏览: 39
`nlohmann::json` 是 C++ 中非常流行的一个 JSON 库,它使得处理 JSON 数据变得异常简单。下面将向您展示如何使用 `nlohmann::json` 将容器内的数据转换成 JSON 格式。
假设我们有一个简单的结构体和一些标准库容器:
```cpp
#include <iostream>
#include <vector>
#include <map>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
struct Person {
std::string name;
int age;
};
// 让 nlohmann 知道怎么把 Person 类型序列化到 JSON 对象里
void to_json(json& j, const Person& p) {
j = json{{"name", p.name}, {"age", p.age}};
}
int main() {
// 创建一个包含两个元素的 vector<Person> 容器
std::vector<Person> people_vector{
{"张三", 24},
{"李四", 30}
};
// 使用 nlohmann::json 来构造对应的数组形式JSON表示法
auto vec_j = json(people_vector);
// 输出结果给用户看
std::cout << "Vector of Persons as JSON:\n" << pretty_print(vec_j) << '\n';
// 同样地我们可以对 map<string,int> 进行操作得到 key-value 形式的 JSON 表示
std::map<std::string, int> ages_map{ {"apple", 5}, {"orange", 7} };
auto map_j = json(ages_map);
// 打印输出 map 的 JSON 字符串版本
std::cout << "Map[string->integer] as JSON:\n" << pretty_print(map_j) << '\n';
return 0;
}
```
以上代码片段展示了如何从常见的 STL 容器如 `std::vector<>`, 和 `std::map<key_type,value_type>` 转换为等价的 JSON 数组或键值对象,并通过控制台打印出来供调试查看。
为了能够成功运行上述例子,请确保已经安装了 [nlohmann/json](https://github.com/nlohmann/json),并且正确配置好你的项目以便链接此第三方依赖项。
--
阅读全文
相关推荐

















