Open
Description
RapidJSON是一款由腾讯开源的json处理包,我在项目中使用的时候,还有点不太熟悉,所以简单记录一些东西。
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main() {
// official example to parse json
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
// 2. 利用 DOM 作出修改。
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. 把 DOM 转换(stringify)成 JSON。
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
// Build json string
Document jsondoc;
jsondoc.SetObject();
Document::AllocatorType& allocator = jsondoc.GetAllocator();
Value s2;
s2 = "This is value";
jsondoc.AddMember("key2", s2, allocator);
StringBuffer buffer2;
Writer<StringBuffer> writer2(buffer2);
jsondoc.Accept(writer2);
std::cout << buffer2.GetString() << std::endl;
// Build json use already exists string
Document jsondoc3;
jsondoc3.SetObject();
std::string a = "A old string";
Document::AllocatorType& allocator3 = jsondoc3.GetAllocator();
Value s3;
s3.SetString(StringRef(a.c_str())); // This is the special place
jsondoc3.AddMember("test", s3, allocator3);
StringBuffer buffer3;
Writer<StringBuffer> writer3(buffer3);
jsondoc3.Accept(writer3);
std::cout << buffer3.GetString() << std::endl;
return 0;
}
The output is,
{"project":"rapidjson","stars":11}
{"key2":"This is value"}
{"test":"A old string"}