C++操作json
阿新 • • 發佈:2018-12-19
具體操作程式碼如下:
#include<iostream> #include<string> #include "..\\include\\rapidjson\\document.h" #include "..\\include\\rapidjson\\writer.h" #include "..\\include\\rapidjson\\stringbuffer.h" using namespace rapidjson; std::string ToJson() { Document doc; doc.SetObject(); Document::AllocatorType &typeAllocate = doc.GetAllocator(); //單個key doc.AddMember("id", 10, typeAllocate); doc.AddMember("name", "test", typeAllocate); //陣列 Value valueArr(rapidjson::kArrayType); for (int nIndex = 0; nIndex < 2; ++nIndex) { Value valueData(rapidjson::kObjectType); valueData.AddMember("C++", "666", typeAllocate); valueData.AddMember("Java", "1212", typeAllocate); valueArr.PushBack(valueData, typeAllocate); } doc.AddMember("skill", valueArr, typeAllocate); StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); std::string strMsg = buffer.GetString(); std::cout << strMsg.c_str() << std::endl; return strMsg; } void ParseJson(const std::string& strData) { std::cout << "********開始解析json資料***********\n"; Document doc; doc.Parse(strData.c_str()); if (doc.HasParseError()) { std::cout << "解析json失敗,Src:" << strData.c_str() << std::endl; return; } Value &vData = doc["id"]; std::cout << "ID:" << vData.GetInt() << "\n"; vData = doc["name"]; std::cout << "Name:" << vData.GetString() << "\n"; vData = doc["skill"]; for (int nIndex = 0; nIndex < vData.Size(); ++nIndex) { Value& valueSkill = vData[nIndex]; std::cout << "Name:" << valueSkill["C++"].GetString() << ","; std::cout << "Name:" << valueSkill["Java"].GetString() << "\n"; } } int main() { std::string strRst(ToJson()); ParseJson(strRst); system("pause"); return 0; }