#include "rapidjson.h"
#include "prettywriter.h"
#include "document.h"
using namespace std;
string ArrayToJson()
{
using namespace rapidjson;
StringBuffer sb;
PrettyWriter<StringBuffer> writer(sb);
writer.StartArray();
writer.StartObject();
writer.Key("name");
writer.String("xiaoming");
writer.EndObject();
writer.StartObject();
writer.Key("name");
writer.String("xiaohua");
writer.EndObject();
writer.EndArray();
return sb.GetString();
}
生成的效果:
[
{
"name": "xiaoming"
},
{
"name": "xiaohua"
}
]
解析生成的json如下所示:
void ParseArray(string strJson)
{
//创建解析对象
rapidjson::Document doc;
//首先进行解析,没有解析错误才能进行具体字段的解析
if (!doc.Parse(strJson.data()).HasParseError())
{
const rapidjson::Value& docArray = doc.GetArray();
for (int i = 0; i < docArray.Size(); ++i)
{
string strValue = docArray[i]["name"].GetString();
}
}
}