nlohmann json
nlohman json GitHub - nlohmann/json: JSON for Modern C++ 是一个为现代C++(C++11)设计的JSON解析库,主要特点是
易于集成,仅需一个头文件,无需安装依赖
易于使用,可以和STL无缝对接
1、nlohmann的安装与引用
安装地址:
https://link.zhihu.com/?target=https%3A//github.com/nlohmann/json
安装nlohmann/json.hpp非常简单,只需将json.hpp头文件复制到项目的适当位置即可。在C++源文件中,通过包含#include "nlohmann/json.hpp"来引用该库。
2.nlohmann json基础操作
2.1 从文件中读入json
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// ...
//创建一个ofstream对象用于读入文件
std::ofstream f("example.json");
json data = json::parse(f);
2.2各种类型数据获取与设置
获取数据:
使用 get<int>()
、get<double>()
、get<std::string>()
等方法获取数据值。
// 使用get<std::string>()获取字符串类型的数据
std::string name = j["name"].get<std::string>();
std::cout << "Name: " << name << std::endl;
// 使用get<int>()获取整数类型的数据
int age = j["age"].get<int>();
std::cout << "Age: " << age << std::endl;
// 使用get<double>()获取浮点数类型的数据
double height = j["height"].get<double>();
std::cout << "Height: " << height << std::endl;
// 使用get<bool>()获取布尔类型的数据
bool is_student = j["is_student"].get<bool>();
std::cout << "Is Student: " << std::boolalpha << is_student << std::endl;
设置数据:
直接通过 JSON 对象访问和设置值,例如 json["key"] = value
。
// 使用nlohmann::json命名空间
nlohmann::json j;
// 添加数据到JSON对象
j["name"] = "John Doe";
j["age"] = 30;
j["is_student"] = false;
j["grades"] = {88, 92, 77};
2.3获取字符串
// 创建一个 JSON 对象并添加字符串数据
nlohmann::json j = {
{"name", "John Doe"},
{"description", "A JSON library for C++"}
};
// 获取字符串值
std::string name = j["name"].get<std::string>(); // 使用显式类型转换
std::string description = j.at("description").get<std::string>(); //使用 at() 方法可以避免在键不存在时抛出异常,它会在键不存在时抛出 std::out_of_range 异常。
2.4保存到文件:
创建一个std::ofstream
对象,指定要保存的文件名。
使用nlohmann::json
库提供的dump()
方法将JSON对象转换为字符串。
将字符串写入文件。
// 创建一个ofstream对象用于写入文件
std::ofstream outfile("output.json");
// 检查文件是否成功打开
if (!outfile.is_open()) {
std::cerr << "Unable to open file!" << std::endl;
return 1;
}
// 使用dump()方法将JSON对象转换为格式化的字符串
outfile << j.dump(4); // 第二个参数是缩进级别,这里是4个空格
// 关闭文件
outfile.close();
2.5生成字符串
使用 dump()
方法将 JSON 对象转换为字符串。
// 创建一个 JSON 对象
nlohmann::json j;
// 添加数据到 JSON 对象
j["name"] = "John Doe";
j["age"] = 30;
j["is_student"] = false;
j["grades"] = {88, 92, 77};
// 使用 dump() 方法将 JSON 对象转换为字符串
// 第二个参数是缩进级别,这里是 4 个空格,使输出格式化
std::string json_string = j.dump(4);