雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

rapidjson解析json代碼實(shí)例以及常見的json core dump問題

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎ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)自己下載開源的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,不多說,人生苦短,我愛rapidjson

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)我們的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接

上一篇:C++中rapidjson將嵌套map轉(zhuǎn)為嵌套json的講解

欄    目:C語言

下一篇:詳解C++ 臨時(shí)量與臨時(shí)對(duì)象及程序的相關(guān)優(yōu)化

本文標(biāo)題:rapidjson解析json代碼實(shí)例以及常見的json core dump問題

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/340.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有