C++ Json 数据存储
时间: 2023-06-28 21:03:48 浏览: 55
在C++中,可以使用第三方库来处理JSON数据的存储和解析。其中,比较流行的有:
1. RapidJSON:一个快速的、DOM风格的、C++11 JSON解析器和生成器。它具有高性能、低内存占用和易于使用的特点。
2. jsoncpp:一个轻量级的C++ JSON解析器和生成器。它支持标准的JSON格式,并提供了友好的API接口。
3. Boost.PropertyTree:一个基于Boost库的C++属性树库,可以用于处理各种格式的数据,包括JSON。
以下是使用RapidJSON库将JSON数据存储到文件中的示例代码:
```cpp
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <fstream>
using namespace rapidjson;
int main() {
// 创建一个JSON对象
Document doc;
doc.SetObject();
// 添加几个键值对
Value name;
name.SetString("Tom", doc.GetAllocator());
doc.AddMember("name", name, doc.GetAllocator());
Value age;
age.SetInt(20);
doc.AddMember("age", age, doc.GetAllocator());
Value hobbies;
hobbies.SetArray();
Value hobby1;
hobby1.SetString("reading", doc.GetAllocator());
hobbies.PushBack(hobby1, doc.GetAllocator());
Value hobby2;
hobby2.SetString("sports", doc.GetAllocator());
hobbies.PushBack(hobby2, doc.GetAllocator());
doc.AddMember("hobbies", hobbies, doc.GetAllocator());
// 将JSON对象转换成字符串
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
std::string jsonStr = buffer.GetString();
// 将JSON字符串存储到文件中
std::ofstream ofs("data.json");
if (ofs.is_open()) {
ofs << jsonStr;
ofs.close();
}
return 0;
}
```
该示例代码创建了一个JSON对象,添加了几个键值对,并将其转换成字符串后存储到文件中。文件内容如下所示:
```json
{"name":"Tom","age":20,"hobbies":["reading","sports"]}
```