jsoncpp
1.jsoncpp配置
1、首先下载jsoncpp。下载链接:https://github.com/open-source-parsers/jsoncpp
2、下载好之后,解压到本地文件,我们解析JSON文件一般只需要文件中的include文件和src文件。
3、创建解析JSON文件的工程,然后把这两个文件复制到工程目录中
4、配置项目的依赖库
右击项目 -》属性 -》C\C++ -》常规 -》附加包含目录,添加依赖
5、把src文件中lib_json下的.cpp文件导入目录
6、包含头文件"json/json.h"
2.c++操作json文件
2.1各种数据类型的获取与设置
获取数据:
int age = root["age"].asInt();
double height = root["height"].asDouble();
std::string name = root["name"].asString();
bool isStudent = root["is_student"].asBool(); // 使用 asBool() 获取布尔值
存储数据:
Json::Value root; // 创建一个 Json::Value 对象root
// 存储整型
root["age"] = 25;
// 存储双精度浮点数
root["height"] = 1.75;
// 存储字符串
root["name"] = "John Doe";
// 存储布尔值
root["is_student"] = false;
设置数据值:
root["new_key"] = new_value; // new_value 可以是 int、double、std::string 等
定义 JSON 字符串:
const std::string jsonString = R"(
{
"name": "Sherry",
"age": 30,
"is_student": false,
"height": 1.76,
}
)";
2.2保存到文件
使用 Json::StreamWriterBuilder写入文件:
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = " "; // 设置缩进为3个空格
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
writer->write(root);
std::cout << writer->asString(); // 输出到控制台
// 写入文件
std::ofstream outFile("output.json");
outFile << writer->asString();
outFile.close();
2.3从字符串中解析
使用 Json::Reader和 parse()方法解析JSON字符串
//创建一个Json::Reader对象
Json::Reader reader;
//定义JSON字符串
const std::string jsonString = R"(
{
"name": "John",
"age": 18,
"is_student": true,
"height": 1.75,
}
)";
//使用 parse()方法解析JSON 字符串
Json::Value root;
bool parsingSuccessful = reader.parse(jsonString, root);
2.4生成字符串
创建 Json::Value对象并填充数据:
Json::Value root;
root["name"] = "John Doe";
root["age"] = 30;
root["is_student"] = false;
root["height"] = 1.75;
创建 Json::StreamWriterBuilder对象:
Json::StreamWriterBuilder builder;
使用 Json::StreamWriterBuilder创建 Json::StreamWriter 对象
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
//unique_ptr:C++ 11标准中智能指针
将 Json::Value对象转换为字符串:
std::string jsonString = writer->write(root);