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

今天小编就为大家分享一篇关于rapidjson解析json代码实例以及常见的json core dump问题,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

rapidjson解析json代码实例

直接看代码:

 #include  #include  #include #include  #include  #include  #include // 请自己下载开源的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代码实例以及常见的json core dump问题的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言