C++之RapidJSON解析json數據
線上幽靈 2019-05-26 10:20:15
————————————————
版權聲明:本文為CSDN博主「線上幽靈」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/chen134225/article/details/90573407
RapidJSON 是一個 C++ 的 JSON 解析器及生成器。
JSON文本:
{ "name": "xiaoming", "gender": "boy", "hobby": ["足球", "籃球", "電影"], "socre": { "數學": 91.5, "英語": 96.0, "語文": 95.5 }, "lover": { "name": "xiaohong", "gender": "girl", "hobby": ["畫畫", "跳舞", "唱歌"], "score": { "數學": 78.5, "英語": 90.0, "語文": 89.0 } } }
由於復制的過程中,json文本可以出現錯誤,可以用將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; } } } }
輸出結果: