rapidjson嵌套json解析及生成
ranpidjson解析库自取链接:
https://pan.baidu.com/s/1VS50seetsqrBilXLI997fQ
提取码:rnhd
#include <fstream>
#include <string>
#include <vector>
#include <atlstr.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/pointer.h"
void JsonSerialize();
void JsonDeserialize(CString cstrJson);
void main()
{
JsonSerialize();
CString cstrJson = "{\"cmd\": \"start\",\"group\":[{\"name\": \"Var1\",\"value\": \"100\",\"format\":9},{\"name\": \"Var2\",\"value\": \"245\",\"format\":16},\
{\"name\": \"Var3\",\"value\": \"356\",\"format\":40}]}";
JsonDeserialize(cstrJson);
return;
}
void JsonSerialize()
{
//{"code":200,"group":[{"Name":"Jane","Id":123},{"Name":"Faker","Id":456},{"Name":"Theshy","Id":789}]}
std::string strName[3] = {"Jane", "Faker", "Theshy"};
long plAck[3] = {123, 456, 789};
rapidjson::Document doc;
rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
doc.SetObject();
doc.AddMember("code",200,allocator);
rapidjson::Value vArray(rapidjson::kArrayType);
for(int nIndex = 0; nIndex < 3; ++nIndex)
{
rapidjson::Value vObject(rapidjson::kObjectType);
vObject.AddMember("Name",rapidjson::StringRef(strName[nIndex].c_str()),allocator);
vObject.AddMember("Id",plAck[nIndex],allocator);
vArray.PushBack(vObject,allocator);
}
doc.AddMember("group",vArray,allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer2(buffer);
doc.Accept(writer2);
std::ofstream out("./Simple.json");
std::string strTmp = buffer.GetString();
out << strTmp << std::endl;
out.close();
return;
}
void JsonDeserialize(CString cstrJson)
{
//{"cmd": "start","group":[{"name": "Var1","value": "100","format": 9},{"name": "Var2","value": "245","format": 16},\
{"name": "Var3","value": "356","format": 40}]}
rapidjson::Document ProObj;
ProObj.Parse<0>(cstrJson);
std::string strCmd;
std::vector<std::string> vecName;
std::vector<std::string> vecValue;
std::vector<int> vecFormat;
if (!ProObj.HasParseError())
{
if(ProObj.HasMember("cmd"))
{
strCmd = ProObj["cmd"].GetString();
}
if(ProObj.HasMember("group"))
{
rapidjson::Value& vCmdGroup = ProObj["group"];
if(vCmdGroup.IsArray())
{
for(rapidjson::SizeType i = 0;i < vCmdGroup.Size();i++)
{
if(vCmdGroup[i].HasMember("name") && vCmdGroup[i]["name"].IsString())
{
vecName.push_back(vCmdGroup[i]["name"].GetString());
}
if(vCmdGroup[i].HasMember("value") && vCmdGroup[i]["value"].IsString())
{
vecValue.push_back(vCmdGroup[i]["value"].GetString());
}
if(vCmdGroup[i].HasMember("format") && vCmdGroup[i]["format"].IsInt())
{
vecFormat.push_back(vCmdGroup[i]["format"].GetInt());
}
}
}
}
}
return;
}
如需转载请获取本人许可。