C++之RapidJSON解析json数据
是⼀个 C++ 的 JSON 解析器及⽣成器。
JSON⽂本:
//document.json
{"name":"xiaoming","gender":"boy","hobby":["⾜球","篮球","电影"],"socre":{"数学":91.5,"英语":96.0,"语⽂":95.5},"lover":{"name":"xiaohong","gender":"girl","ho bby":["画画","跳舞","唱歌"],"score":{"数学":78.5,"英语":90.0,"语⽂":89.0}}}
由于复制的过程中,json⽂本可以出现错误,可以⽤将json⽂本复制到验证⼀下。
解析代码:
#include<string>
#include<fstream>
#include<iostream>
#include"document.h"
using namespace std;
int main () {
std::ifstream t("./document.json");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
rapidjson::Document document;
document.Parse(str.c_str());
rapidjson::Value::ConstMemberIterator iter = document.FindMember("name");
if(iter != document.MemberEnd()){
cout << "name : " << iter->value.GetString() << endl;
}
iter = document.FindMember("gender");
if(iter != document.MemberEnd()){
cout << "gender : " << iter->value.GetString() << endl;
}
if(document.HasMember("hobby")){
cout << "hobby : " << endl;
const rapidjson::Value& childValue = document["hobby"];
for(rapidjson::SizeType i = 0; i < childValue.Size(); ++i){
cout << " " << childValue[i].GetString() << endl;
}
}
if(document.HasMember("score")){
cout << "score : " << endl;
const rapidjson::Value& childIter = document["score"];
for(rapidjson::Value::ConstMemberIterator it = childIter.MemberBegin(); it != childIter.MemberEnd(); ++it){
cout << " " << it->name.GetString() << " : " << it->value.GetDouble() << endl;
}
}
if(document.HasMember("lover")){
cout << "lover : " << endl;
const rapidjson::Value& chileValue = document["lover"];
rapidjson::Value::ConstMemberIterator chileIter = chileValue.FindMember("name");
if(chileIter != chileValue.MemberEnd()){
cout << " " << "name : " << chileIter->value.GetString() << endl;
}
chileIter = chileValue.FindMember("gender");
if(chileIter != chileValue.MemberEnd()){
cout << " " << "gender : " << chileIter->value.GetString() << endl;
}
if(chileValue.HasMember("hobby")){
cout << " " << "hobby : " << endl;
const rapidjson::Value& chile2Value = chileValue["hobby"];
for(rapidjson::SizeType i = 0; i < chile2Value.Size(); ++i){
cout << " " << chile2Value[i].GetString() << endl;
}
}
if(chileValue.HasMember("score")){
cout << " " << "score : " << endl;
const rapidjson::Value& child2Iter = chileValue["score"];
for(rapidjson::Value::ConstMemberIterator it = child2Iter.MemberBegin(); it != child2Iter.MemberEnd(); ++it){ cout << " " << it->name.GetString() << " : " << it->value.GetDouble() << endl;
}
}
}
}
输出结果:安卓在线解析json
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论