程序猿 程序猿

RapidJson常规操作总结

in 技术教程 阅读[842] ShiKun 文章转载请注明来源!

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
最后由ShiKun修改于2018-09-17 16:03
发表新评论
雷姆
拉姆