一、介绍
RapidJSON是一个C++的JSON解析器及生成器。它小而全、速度快、独立(不依赖stl、broost)、对内存友好(在大部分32/64位机器上,每个JSON值只占16位(字符串除外)、对Unicode友好(支持UTF-8、UTF-16、UTF-32)。且跨平台(支持Windows.Cygwin.MacOS.iOS.Android)
它的源码在GitHub - Tencent/rapidjson: A fast JSON parser/generator for C++ with both SAX/DOM style API
二、安装
只有头文件的C++库,只需要把include/rapidjson目录复制到系统或项目的include目录中。
三、使用
json文件
{
"kkk": [
0
],
"mmm": [
94
],
"pop": [
66,
91,
106
]
}
#include <fstream>
#include <map>
#include <vector>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace std;
using namespace rapidjson;
// 读取文件
string ReadFile()
{
ifstream file;
file.open("my.json", ios_base::in); // 我的文件名称是my.json
if (!file.is_open())
{
cout << "打开失败";
}
stringstream ss{};
ss << file.rdbuf();
string str = ss.str();
cout << str << endl;
return str;
}
int main()
{
map<string, vector<int>> myData;
string json_content = ReadFile();
rapidjson::Document document;
document.Parse(json_content.c_str());
for (Value::ConstMemberIterator iter = document.MemberBegin();
iter != document.MemberEnd(); ++iter)
{
vector<int> ans;
if (iter->value.IsArray()) {
const rapidjson::Value& temp = document[iter->name.GetString()];
for (SizeType i = 0; i < temp.Size(); ++i) {
ans.push_back(temp[i].GetFloat());
}
}
else if (iter->value.IsInt()) {
int temp = iter->value.GetInt();
ans.push_back(temp);
}
myData[iter->name.GetString()] = ans;
}
system("pause");
return 0;
}
参考: