头文件
#include "document.h" #include "prettywriter.h" #include "filereadstream.h" #include "filewritestream.h" #include "stringbuffer.h"
using namespace rapidjson;
输出json
std::map<int, POINT> shootMap ; string strJson; std::vector<int> everyLoopCount; string str="abc"; int i=0; Document document; Document::AllocatorType& allocator = document.GetAllocator(); Value root(kObjectType); Value fixedPoint(kArrayType);//map读取 Value everyLoop(kArrayType);//vector读取 string strX; string strY; string strloop; //map读取,里面存着POINT类型 for (auto iter = shootMap.begin(); iter != shootMap.end(); ++iter) { Value arrayBody(kArrayType); strX = to_string(iter->second.x); item.SetString(strX.c_str(), strX.size(), allocator); arrayBody.PushBack(item, allocator); strY = to_string(iter->second.y); item.SetString(strY.c_str(), strY.size(), allocator); arrayBody.PushBack(item, allocator); fixedPoint.PushBack(arrayBody, allocator); } //vector 读取,里面存着int类型 for (auto it = everyLoopCount.begin(); it != everyLoopCount.end(); ++it) { Value arrayBody(kArrayType); strloop = to_string(*it); item.SetString(strloop.c_str(), strloop.size(), allocator); arrayBody.PushBack(item, allocator); everyLoop.PushBack(arrayBody, allocator); } //map输出 root.AddMember("map", fixedPoint, allocator); //字符串输出 root.AddMember("字符串", StringRef(str.c_str()), allocator); //vector root.AddMember("vector", everyLoop, allocator); //int root.AddMember("int", i, allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); root.Accept(writer); strJson = buffer.GetString();
读取json
Document doc; doc.Parse<0>(strJson.c_str());
Value & map= doc["map"];
Value & str= doc["字符串"];
Value & vector= doc["vector"];
Value & int= doc["int"];
//输出到map里
POINT targetPoint;
string temp;
int nKey = 0;
if (map.IsArray())
{
for (size_t i = 0; i < map.Size(); ++i)
{
Value & v = map[i];
if (v.IsArray())
{
Value& col = v[0];
temp = col.GetString();
targetPoint.x = atoi(temp.c_str());
col = v[1];
temp = col.GetString();
targetPoint.y = atoi(temp.c_str());
}
rMap.insert(map<int, POINT>::value_type(nKey, targetPoint));
++nKey;
}
}
temp.empty();
//vector
if (scoreValue.IsArray())
{
for (size_t i = 0; i < scoreValue.Size(); ++i)
{
Value & v = scoreValue[i];
if (v.IsArray())
{
Value& col = v[0];
temp = col.GetString();
scores = atof(temp.c_str());
}
score->push_back(scores);
}
}
string str=字符串.GetString();
int i=i.Getint();