array 数组
#include <iostream>
#include <rapidjson.h>
#include <prettywriter.h>
#include <filereadstream.h>
#include <stringbuffer.h>
#include <document.h>
using namespace std;
using namespace rapidjson;
int main(int argc, const char * argv[]) {
Document document;
Document::AllocatorType &allocator = document.GetAllocator();
Value contact1(kArrayType) ;
Value contact2(kArrayType) ;
Value root(kArrayType);
contact1.PushBack("7,3,1", allocator).PushBack("0", allocator).PushBack("1", allocator);
contact2.PushBack("7,3,9", allocator).PushBack("1", allocator).PushBack("0", allocator);
root.PushBack(contact1, allocator);
root.PushBack(contact2, allocator);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
root.Accept(writer);
string reststr = buffer.GetString();
cout << reststr << endl;
Document doc;
if(doc.Parse(reststr.c_str()).HasParseError())
{
cout << "error" << endl;
}
Document::ValueIterator it = doc.Begin();
Document::ValueIterator ed = doc.End();
while(it != ed )
{//解析数组
int len = it->Capacity();
cout << (*it)[1].GetInt() << endl;
for(int i = 0; i < len; ++i)
{
cout << (*it)[i].GetString() << endl;
}
++it;
}
return 0;
}
对象
#include <iostream>
#include <rapidjson.h>
#include <prettywriter.h>
#include <filereadstream.h>
#include <stringbuffer.h>
#include <document.h>
using namespace std;
using namespace rapidjson;
int main(int argc, const char * argv[]) {
Document document;
Document::AllocatorType& allocator = document.GetAllocator();
Value root(kArrayType);
Value items(kObjectType);
Value val(kStringType);
val.SetInt(5);
items.AddMember("test", val, allocator);
val.SetInt(10);
items.AddMember("world", val, allocator);
root.PushBack(items, allocator);
items.SetObject();
val.SetInt(5);
items.AddMember("test", val, allocator);
val.SetInt(10);
items.AddMember("world", val, allocator);
root.PushBack(items, allocator);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
root.Accept(writer);
std::string result = buffer.GetString();
Document rd;
if(rd.Parse(result.c_str()).HasParseError())
{
cout << "error!" << endl;
}
Document::ValueIterator it = rd.Begin();
Document::ValueIterator ed = rd.End();
while(it != ed)
{
Document::MemberIterator iit = it->MemberBegin();
Document::MemberIterator eed = it->MemberEnd();
while(iit != eed )
{
cout << iit->name.GetString() << " " << iit->value.GetInt() << endl;
++iit;
}
++it;
}
return 0;
}