nlohmann json 用法
nlohmann json是一个C++的开源JSON解析器和生成器,其设计目标是提供一个简单而优美的API,并且尽可能地避免任何非必需的内存分配。
使用nlohmann json,你可以方便地将JSON字符串转换成C++对象,并且可以快速地将C++对象转换成JSON字符串。此外,它还支持STL容器,可以很方便地将C++容器转换成JSON对象,也能够将JSON对象转换成C++容器。
以下是nlohmann json的使用方法:
1. 引入头文件
```
#include <nlohmann/json.hpp>
using json = nlohmann::json;
```
2. JSON字符串转换成C++对象
```
// 从JSON字符串中反序列化出C++对象
json j = json::parse("{ \"happy\": true, \"pi\": 3.141 }");
// 从C++对象中获取JSON值
bool is_happy = j["happy"];
double pi = j["pi"];
```
3. C++对象转换成JSON字符串
```
// 将C++对象序列化成JSON字符串
json j;
j["happy"] = true;
j["pi"] = 3.141;
std::string s = j.dump(); // {"happy":true,"pi":3.141}
// 带格式输出
std::cout << j.dump(4) << std::endl;
```
4. 使用STL容器
```
// 转换C++容器为JSON对象
std::map<std::string, int> city_population = { {"Shanghai", 24256800}, {"Beijing", 21710000} };
json j = city_population;json转换对象
// 转换JSON对象为C++容器
std::map<std::string, int> city_population = j.get<std::map<std::string, int>>();
```
总体而言,nlohmann json提供了简单易用的API,支持标准C++,性能优良,可靠稳定。所以它是一个非常好的JSON库选择,特别是对于那些需要在C++程序中使用JSON的开发者。