加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

rapidjson解析json代码实例以及常见的json core dump问题

发布时间:2020-12-16 19:02:08 所属栏目:百科 来源:网络整理
导读:直接看代码: #include iostream#include stdio.h#includeunistd.h#include sys/types.h#include sys/stat.h#include fcntl.h#includesstream// 请自己下载开源的rapidjson#include "rapidjson/prettywriter.h"#include "rapidjson/rapidjson.h"#include "ra

直接看代码:

#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 = "{"code":0,"msg":"ok"}";
	cout << s << endl;
	cout << getStringFromJson(s,"msg") << endl;
	return 0;
}
结果:

{"code":0,"msg":"ok"}
ok


注意:

1. 如果不进行document.Parse(jsStr.c_str()).HasParseError()判断, 则很容易core dump

2. 如果不进行!document.HasMember(strKey.c_str())判断, 则很容易core dump

3. code的是为0, 是整数, 如果调用上述getStringFromJson, 会core dump,此时应该用return jv.GetInt();


OK,不多说, 人生苦短, 我爱rapidjson

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读