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

Agnes ·
更新时间:2024-09-21
· 791 次阅读

rapidjson解析json代码实例

直接看代码:

#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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对软件开发网的支持。如果你想了解更多相关内容请查看下面相关链接

您可能感兴趣的文章:利用rapidjson实现解析嵌套的json的方法示例C++中rapidjson组装继续简化的方法C++中rapidjson将嵌套map转为嵌套json的讲解C++中rapidjson将map转为json的方法C++中rapidjson组装map和数组array的代码示例小程序getLocation需要在app.json中声明permission字段Node.js中package.json中库的版本号(~和^)Go JSON编码与解码的实现使用post方法实现json往返传输数据的方法json error: Use of overloaded operator [] is ambiguous错误的解决方法



rapidjson dump core

需要 登录 后方可回复, 如果你还没有账号请 注册新账号