RapidJson常规操作总结

技术教程 · 2018-09-17

RapidJson是只需包含头文件就可以直接使用的第三方json解析库

1.包含头文件

#include "rapidjson/document.h"  
#include "rapidjson/stringbuffer.h" 
#include "rapidjson/writer.h" 

2.声明一些变量

Document doc;
doc.SetObject();

Document::AllocatorType& alloc = doc.GetAllocator();

Value key(kStringType);  
Value value(kStringType); 

3.添加节点与赋值

key.SetString("name", alloc);  
value.SetString("kun775", alloc);  
doc.AddMember(key, value, alloc);

4.数组

Value array(rapidjson::kArrayType); 
Value child(kObjectType);

key.SetString("name", alloc);  
value.SetString("kun775", alloc);  
child.AddMember(key, value, alloc);

array.PushBack(child, alloc);  

key.SetString("name", alloc);  
value.SetString("somebody", alloc);  
child.AddMember(key, value, alloc);

array.PushBack(child, alloc);  

5.序列化与打印

StringBuffer sbuffer;      // in rapidjson/stringbuffer.h
Writer<StringBuffer> writer(sbuffer); // in rapidjson/writer.h
//array.Accept(writer);
doc.Accept(writer);

logDebug("%s", sbuffer.GetString());
rapidjson
Theme Jasmine by Kent Liao