0%

cpp 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
44
45
46
47
const char *json = "{
"hello": "world",
"t": true ,
"f": false,
"n": null,
"i": 123,
"pi": 3.1416,
"a": [1, 2, 3, 4]
}";

Document document;
// 1. 解析
document.Parse(json);

// 2. 读取值
assert(document.HasMember("hello"));
assert(document["hello"].IsString());
printf("hello = %s\n", document["hello"].GetString());

// 3. 新建值
Value v;
v = "hello";
document.AddMember("key", v, document.GetAllocator());

// 4. 序列化成字符串
StringBuffer str;
Writer<StringBuffer> writer(str);
document.Accept(writer);
cout << strBuffer.GetString() << endl;

// 5. 从文件读入
FILE* fp = fopen("big.json", "r"); // 非 Windows 平台使用 "r"
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
Document d;
d.ParseStream(is);
fclose(fp);

// 6. 写入文件
Document d;
d.Parse(json);
FILE* fp = fopen("output.json", "w"); // 非 Windows 平台使用 "w"
char writeBuffer[65536];
FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
d.Accept(writer);
fclose(fp);