rapidjson 相較於 jsoncpp 最方便的一點就在於在c++ 項目中只需要包含rapidjson 的頭文件就能使用,而jsoncpp 需要使用相同平台下編譯出來的lib文件進行使用,用起來沒有rapidjson 方便。
通過開源作者的說明,rapidjson 速度快,性能可與strlen() 相比。
以下是一些關於rapidjson 的簡單用法:
使用之前只需要將對應的頭文件包含進來
#include "include/rapidjson/document.h" #include "include/rapidjson/writer.h" #include "include/rapidjson/stringbuffer.h" using namespace rapidjson;
讀取一個json 字符串對象數組。
//其中包含簡單的字符對象,對象數組 const char* str = "{\"uploadid\": \"UP000000\",\"code\": [{\"code\":100}],\"msg\": \"study\",\"files\": \"\"}"; Document d; d.Parse(str); Value& s = d["code"]; assert(s.IsArray()); Value &v = s[0]; assert(v.IsObject()); int n = v["code"].GetInt(); StringBuffer buffer; Writer<StringBuffer> writer(buffer); //將json 中的數據轉換成字符串形式 d.Accept(writer); cout << buffer.GetString() << endl;
組裝一個json 字符串
Document d; Document::AllocatorType &allocator = d.GetAllocator(); //索引器 d.SetObject(); //創建一個對象在DOM下 Value ItemTmp(kArrayType); //創建一個數組元素 //插入一個string 類型對象 Value obj(kObjectType); Value strValue; strValue.SetString(str,allocator); //插入一個double 類型對象 Value Tmp; Tmp.SetDouble(ask); obj.AddMember("ask_price", Tmp, allocator); /* ................................................ */ ItemTmp.PushBack(obj, allocator); //將這個對象數組插入到DOM數組中去 d.AddMember("data", ItemTmp, allocator); //這個對象數組在data這個對象下 //將json對象轉換成string類型輸出 StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); std::string strData = buffer.GetString();