利用rapidjson實現(xiàn)解析嵌套的json的方法示例
利用rapidjson解析嵌套的json
看json串1:{"system":{"version":"v2.6.1", "name":"value"}}
廢話少說, 直接擼代碼:
#include <iostream> #include <stdio.h> #include<unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<sstream> // 請自己下載開源的rapidjson #include "rapidjson/prettywriter.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "rapidjson/memorystream.h" using namespace std; using rapidjson::Document; using rapidjson::StringBuffer; using rapidjson::Writer; using namespace rapidjson; string getVersion(const string &jvStr) { Document document; if (document.Parse(jvStr.c_str()).HasParseError() || !document.HasMember("system")) { return ""; } const rapidjson::Value &jvObject = document["system"]; if(!jvObject.IsObject()) { return ""; } if(!jvObject.HasMember("version")) { return ""; } const rapidjson::Value &jv = jvObject["version"]; return jv.GetString(); } int main(int argc, char *argv[]) { string s = "{\"system\":{\"version\":\"v2.6.1\", \"name\":\"value\"}}"; cout << s << endl; cout << getVersion(s) << endl; return 0; }
結果:
{"system":{"version":"v2.6.1", "name":"value"}}
v2.6.1
再看字符串:{"system": "{\"version\":\"v2.6.1\", \"name\":\"value\"}"}
直接上馬:
#include <iostream> #include <stdio.h> #include<unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<sstream> // 請自己下載開源的rapidjson #include "rapidjson/prettywriter.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "rapidjson/memorystream.h" using namespace std; using rapidjson::Document; using rapidjson::StringBuffer; using rapidjson::Writer; using namespace rapidjson; string getStringFromJson(const string &jsStr, const string &strKey) { Document document; if (document.Parse(jsStr.c_str()).HasParseError() || !document.HasMember(strKey.c_str())) { return ""; } const rapidjson::Value &jv = document[strKey.c_str()]; return jv.GetString(); } int main(int argc, char *argv[]) { string s = "{\"system\": \"{\\\"version\\\":\\\"v2.6.1\\\", \\\"name\\\":\\\"value\\\"}\"}"; cout << s << endl; string str = getStringFromJson(s, "system"); cout << str << endl; cout << getStringFromJson(str, "version") << endl; return 0; }
結果:
{"system": "{\"version\":\"v2.6.1\", \"name\":\"value\"}"}
{"version":"v2.6.1", "name":"value"}
v2.6.1
第二種方式的json串,看起來太惡心了。
另外,再次強調一下,json串解析的時候,容易core dump,所以要做好異常判斷,也要注意類型。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
- rapidjson解析json代碼實例以及常見的json core dump問題
- C++中rapidjson組裝繼續(xù)簡化的方法
- C++中rapidjson將嵌套map轉為嵌套json的講解
- C++中rapidjson將map轉為json的方法
- C++中rapidjson組裝map和數(shù)組array的代碼示例
- 小程序getLocation需要在app.json中聲明permission字段
- Node.js中package.json中庫的版本號(~和^)
- Go JSON編碼與解碼的實現(xiàn)
- 使用post方法實現(xiàn)json往返傳輸數(shù)據(jù)的方法
- json error: Use of overloaded operator [] is ambiguous錯誤的解決方法