/*! * Email: guxuanqing@gmail.com * Auth: xor * Date: 2019-5-17 * File: vectorPtr.cpp * Class: %{Cpp:License:ClassName} (if applicable) * Brief: * Note: */ #include <bits/stdc++.h> #include <unistd.h> #include "rapidjson/document.h" #include "rapidjson/writer.h" //#include "rapidjson/filestream.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" using namespace std; using namespace rapidjson; struct GENERALDATA{ int m_data; char m_buf[16]; }; struct DATATEST{ vector<GENERALDATA> vecData; }; void vecToJsonFunc(void *req, void *rsp) { DATATEST *dtest = static_cast<DATATEST *>(req); // rsp DATATEST *pRsp = static_cast<DATATEST *>(rsp); Document doc; doc.SetObject(); Document::AllocatorType &allocator=doc.GetAllocator(); //获取分配器 doc.AddMember("Auth", "xor",allocator); Value array1(kArrayType); for (int i=0;i<dtest->vecData.size();++i) { GENERALDATA &gend = dtest->vecData[i]; Value object2(kObjectType); Value bufStr(kStringType); string iTostr = to_string(i+100); // allocator -> deep copy bufStr.SetString(iTostr.c_str(), iTostr.size(), allocator); object2.AddMember("buf", bufStr, allocator); Value InOne(kNumberType); InOne.SetInt(gend.m_data); object2.AddMember("mdata", InOne, allocator); array1.PushBack(object2, allocator); } doc.AddMember("Numbers", array1, allocator); StringBuffer buffer; PrettyWriter<StringBuffer> pretty_writer(buffer); //PrettyWriter是格式化的json,如果是Writer则是换行空格压缩后的json doc.Accept(pretty_writer); cout<< "output composed buf:" << buffer.GetString()<<endl; // parse string readJsonStr = buffer.GetString(); Document docParser; docParser.Parse(readJsonStr.c_str()); // Value &author = docParser["Auth"]; if(docParser.HasMember("Numbers") && docParser["Numbers"].IsArray()) { const Value &ArrayObject = docParser["Numbers"]; for (size_t i = 0; i < ArrayObject.Size(); ++i) { const Value &v = ArrayObject[i]; GENERALDATA geneData; if (v.IsObject()) { if (v.HasMember("mdata") && v["mdata"].IsInt()) { geneData.m_data = v["mdata"].GetInt(); } if(v.HasMember("buf") && v["buf"].IsString()) { strncpy(geneData.m_buf, v["buf"].GetString(), sizeof (geneData.m_buf)); } } pRsp->vecData.emplace_back(geneData); } } //abort if(docParser.HasMember("room") && docParser["room"].IsString()) { cout << docParser["room"].GetString() << endl; } Value &author = docParser["Auth"]; printf("I will sleep 10s "); sleep(10); //system("pause"); } int main(int argc,char **argv){ DATATEST tst; for(int i=0;i<5;++i) { GENERALDATA dt; dt.m_data = i; tst.vecData.emplace_back(dt); } DATATEST tstRsp; vecToJsonFunc(&tst, &tstRsp); printf("hello world! "); return 0; }
上文json串
{ "Auth": "xor", "Numbers": [ { "buf": "100", "mdata": 0 }, { "buf": "101", "mdata": 1 }, { "buf": "102", "mdata": 2 }, { "buf": "103", "mdata": 3 }, { "buf": "104", "mdata": 4 } ] }