rapidjson使用總結


Reference:  https://blog.csdn.net/elloop/article/details/49908689

rapidjson簡介

rapidjson是騰訊的開源json解析框架,用c++實現。由於全部代碼僅用header file實現,所以很容易集成到項目中。

rapidjson的性能是很出色的,其作者Milo Yipz做了28個C/C++ JSON庫的評測,這個鏈接里有測試的結果截圖。

rapidjson的另一個特點是對json的標准符合程度是100%的(在開啟了full precision選項的情況下)。

這里是官方教程:rapidjson官方教程

這里是原作者對rapidjson代碼的剖析:rapidjson代碼剖析

我之前的項目使用的是jsoncpp,最近在把解析json的代碼交叉編譯到iOS設備的時候,偶爾會出現crash的情況。雖然經過檢查是代碼寫的有問題,不是jsoncpp的問題,在解決問題過程中嘗試了rapidjson這個庫,並順便對比了一下jsoncpp和rapidjson對我項目中json文件的解析速度。

Dom解析示例

下面是我寫的一個小例子,從test.json文件中讀取內容並解析。其他代碼示例也可以查看我的github倉庫中關於rapidjson的測試代碼:rapid_json_test.cpp.

// test.json
{
    "dictVersion": 1, "content": [ {"key": "word1", "value": "單詞1"} , {"key": "word2", "value": "單詞2"} , {"key": "word3", "value": "單詞3"} , {"key": "word4", "value": "單詞4"} , {"key": "word5", "value": "單詞5"} ] }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
// test.cpp #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include <fstream> #include <string> #include <cassert> #include <iostream> #define psln(x) std::cout << #x " = " << (x) << std::endl void testSimpleDoc() { using std::string; using std::ifstream; // read json content into string. string stringFromStream; ifstream in; in.open("test.json", ifstream::in); if (!in.is_open()) return; string line; while (getline(in, line)) { stringFromStream.append(line + "\n"); } in.close(); // ---------------------------- read json -------------------- // parse json from string. using rapidjson::Document; Document doc; doc.Parse<0>(stringFromStream.c_str()); if (doc.HasParseError()) { rapidjson::ParseErrorCode code = doc.GetParseError(); psln(code); return; } // use values in parse result. using rapidjson::Value; Value & v = doc["dictVersion"]; if (v.IsInt()) { psln(v.GetInt()); } Value & contents = doc["content"]; if (contents.IsArray()) { for (size_t i = 0; i < contents.Size(); ++i) { Value & v = contents[i]; assert(v.IsObject()); if (v.HasMember("key") && v["key"].IsString()) { psln(v["key"].GetString()); } if (v.HasMember("value") && v["value"].IsString()) { psln(v["value"].GetString()); } } } // ---------------------------- write json -------------------- pcln("add a value into array"); Value item(Type::kObjectType); item.AddMember("key", "word5", doc.GetAllocator()); item.AddMember("value", "單詞5", doc.GetAllocator()); contents.PushBack(item, doc.GetAllocator()); // convert dom to string. StringBuffer buffer; // in rapidjson/stringbuffer.h Writer<StringBuffer> writer(buffer); // in rapidjson/writer.h doc.Accept(writer); psln(buffer.GetString()); }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM