rapidjson解析json代碼實(shí)例以及常見(jiàn)的json core dump問(wèn)題
rapidjson解析json代碼實(shí)例
直接看代碼:
#include <iostream>
#include <stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<sstream>
// 請(qǐng)自己下載開(kāi)源的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 = "{\"code\":0,\"msg\":\"ok\"}";
cout << s << endl;
cout << getStringFromJson(s, "msg") << endl;
return 0;
}
結(jié)果:
{"code":0,"msg":"ok"}
ok
注意:
1. 如果不進(jìn)行document.Parse(jsStr.c_str()).HasParseError()判斷,則很容易core dump
2. 如果不進(jìn)行!document.HasMember(strKey.c_str())判斷,則很容易core dump
3. code的是為0,是整數(shù),如果調(diào)用上述getStringFromJson,會(huì)core dump,此時(shí)應(yīng)該用return jv.GetInt();
OK,不多說(shuō),人生苦短,我愛(ài)rapidjson
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
C++ 中實(shí)現(xiàn)把EXCEL的數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(kù)(ACCESS、MSSQL等)實(shí)例代碼
這篇文章主要介紹了C++ 中實(shí)現(xiàn)把EXCEL的數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫(kù)(ACCESS、MSSQL等)實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-04-04
C++實(shí)現(xiàn)LeetCode(147.鏈表插入排序)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(147.鏈表插入排序),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單掃雷小程序
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單掃雷小程序,一款大眾類的益智小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10
Qt簡(jiǎn)單編程實(shí)現(xiàn)UDP通訊
UDP數(shù)據(jù)報(bào)協(xié)議是一個(gè)面向無(wú)連接的傳輸層報(bào)文協(xié)議,它簡(jiǎn)單易用,不存在?TCP協(xié)議“粘包”的問(wèn)題,下面我們就來(lái)看看如何使用qt簡(jiǎn)單實(shí)現(xiàn)UDP通訊吧2024-04-04

