rapidjson创建型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include <string>
using namespace std;
using namespace rapidjson;
int main() {
Document d;
d.SetObject();
std::string s = "123";
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
//生成含有数组的document,注意在rapidjson中所有的数据都是一个Value,数组的本质也是一个Array;
rapidjson::Value arr(rapidjson::kArrayType);
arr.PushBack("1", allocator);
arr.PushBack("2", allocator);
arr.PushBack(rapidjson::StringRef(s.c_str()), allocator);
//生成数组中包含有多个obj的数组
rapidjson::Value o1;
o1.SetObject();
o1.AddMember("o1", 1, allocator);
arr.PushBack(o1, allocator);
rapidjson::Value o2;
o2.SetObject();
o2.AddMember("o2", 2, allocator);
arr.PushBack(o2, allocator);
d.AddMember("arr", arr, allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<StringBuffer> writer(buffer);
d.Accept(writer);
std::cout << buffer.GetString() << std::endl;
return 0;
}