概述
使用 rapidjson
来解析本地的 json
文件。
本地 json 文件
{
"num": 3,
"subject": [
"Math",
"English",
"Computer Science"
],
"info": [
{
"value": "线性代数",
"score": 70,
"aveScore": 75.8
},
{
"value": "四六级",
"score": 500,
"aveScore": 410.8
},
{
"value": "数据结构",
"score": 88,
"aveScore": 65.4
}
]
}
代码
#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
#include "rapidjson/prettywriter.h"
#include "rapidjson/document.h"
#include "rapidjson/istreamwrapper.h"
using namespace std;
using namespace rapidjson;
//-----------------------------------------------------------------------------
wstring UTF8ToUnicode(const string &s)
{
wstring result;
// 获得缓冲区的宽字符个数
int length = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0);
wchar_t * buffer = new wchar_t[length];
::MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, length);
result = buffer;
delete[] buffer;
return result;
}
//-----------------------------------------------------------------------------
int main()
{
int n;
int score[3];
double aveScore[3];
string strSubject[3];
wstring wsValue[3];
ifstream t("document.json"); // 输入流
IStreamWrapper isw(t);
Document d;
d.ParseStream(isw);
// 获取最简单的单个键的值
assert(d.HasMember("num"));
assert(d["num"].IsInt());
n = d["num"].GetInt();
// 获取数组的值,使用引用来连续访问
assert(d.HasMember("subject"));
const Value& subjectArray = d["subject"];
if (subjectArray.IsArray())
{
for (int i = 0; i < subjectArray.Size(); i++)
{
strSubject[i] = subjectArray[i].GetString();
}
}
// 获取对象中的数组,也就是对象是一个数组
assert(d.HasMember("info"));
const Value& infoArray = d["info"];
if (infoArray.IsArray()) {
for (int i = 0; i < infoArray.Size(); i++) {
const Value& tempInfo = infoArray[i];
string strValue = tempInfo["value"].GetString();
wsValue[i] = UTF8ToUnicode(strValue);
score[i] = tempInfo["score"].GetInt();
aveScore[i] = tempInfo["aveScore"].GetDouble();
}
}
}
网友评论