jsoncpp读写示例
时间: 2023-10-18 14:06:41 浏览: 33
以下是一个使用jsoncpp读写json的示例:
```c++
#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace std;
int main() {
// 创建 JSON 对象
Json::Value root;
// 添加值
root["name"] = "张三";
root["age"] = 18;
root["gender"] = "男";
// 创建数组
Json::Value array;
array.append("item1");
array.append("item2");
array.append("item3");
root["array"] = array;
// 创建嵌套对象
Json::Value nested;
nested["nested_key"] = "nested_value";
root["nested"] = nested;
// 将 JSON 对象写入文件
ofstream ofs("example.json");
ofs << root;
ofs.close();
// 从文件中读取 JSON 对象
ifstream ifs("example.json");
Json::CharReaderBuilder builder;
Json::CharReader * reader = builder.newCharReader();
Json::Value read_root;
JSONCPP_STRING errs;
reader->parse(ifs, ifs, &read_root, &errs);
delete reader;
ifs.close();
// 输出读取结果
cout << "读取结果:" << endl;
cout << "name: " << read_root["name"].asString() << endl;
cout << "age: " << read_root["age"].asInt() << endl;
cout << "gender: " << read_root["gender"].asString() << endl;
cout << "array: " << endl;
for (int i = 0; i < read_root["array"].size(); i++) {
cout << read_root["array"][i].asString() << endl;
}
cout << "nested: " << endl;
cout << "nested_key: " << read_root["nested"]["nested_key"].asString() << endl;
return 0;
}
```
输出结果:
```text
读取结果:
name: 张三
age: 18
gender: 男
array:
item1
item2
item3
nested:
nested_key: nested_value
```
这个示例创建了一个 JSON 对象,添加了一些值、数组和嵌套对象,然后将其写入文件。接着从文件中读取 JSON 对象,并输出读取结果。