rapidjson使用总结
2015-11-18 16:13
1076 查看
rapidjson简介
rapidjson是腾讯的开源json解析框架,用c++实现。由于全部代码仅用header file实现,所以很容易集成到项目中。rapidjson的性能是很出色的,其作者Milo Yipz做了28个C/C++ JSON库的评测,这个链接里有测试的结果截图。
rapidjson的另一个特点是对json的标准符合程度是100%的(在开启了full precision选项的情况下)。
这里是官方教程:rapidjson官方教程
这里是原作者对rapidjson代码的剖析:rapidjson代码剖析
我之前的项目使用的是jsoncpp,最近在把解析json的代码交叉编译到iOS设备的时候,偶尔会出现crash的情况。虽然经过检查是代码写的有问题,不是jsoncpp的问题,在解决问题过程中尝试了rapidjson这个库,并顺便对比了一下jsoncpp和rapidjson对我项目中json文件的解析速度。
Dom解析示例
下面是我写的一个小例子,从test.json文件中读取内容并解析。其他代码示例也可以查看我的github仓库中关于rapidjson的测试代码:rapid_json_test.cpp.// test.json { "dictVersion": 1, "content": [ {"key": "word1", "value": "单词1"} , {"key": "word2", "value": "单词2"} , {"key": "word3", "value": "单词3"} , {"key": "word4", "value": "单词4"} , {"key": "word5", "value": "单词5"} ] }
// test.cpp #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include <fstream> #include <string> #include <cassert> #include <iostream> #define psln(x) std::cout << #x " = " << (x) << std::endl void testSimpleDoc() { using std::string; using std::ifstream; // read json content into string. string stringFromStream; ifstream in; in.open("test.json", ifstream::in); if (!in.is_open()) return; string line; while (getline(in, line)) { stringFromStream.append(line + "\n"); } in.close(); // ---------------------------- read json -------------------- // parse json from string. using rapidjson::Document; Document doc; doc.Parse<0>(stringFromStream.c_str()); if (doc.HasParseError()) { rapidjson::ParseErrorCode code = doc.GetParseError(); psln(code); return; } // use values in parse result. using rapidjson::Value; Value & v = doc["dictVersion"]; if (v.IsInt()) { psln(v.GetInt()); } Value & contents = doc["content"]; if (contents.IsArray()) { for (size_t i = 0; i < contents.Size(); ++i) { Value & v = contents[i]; assert(v.IsObject()); if (v.HasMember("key") && v["key"].IsString()) { psln(v["key"].GetString()); } if (v.HasMember("value") && v["value"].IsString()) { psln(v["value"].GetString()); } } } // ---------------------------- write json -------------------- pcln("add a value into array"); Value item(Type::kObjectType); item.AddMember("key", "word5", doc.GetAllocator()); item.AddMember("value", "单词5", doc.GetAllocator()); contents.PushBack(item, doc.GetAllocator()); // convert dom to string. StringBuffer buffer; // in rapidjson/stringbuffer.h Writer<StringBuffer> writer(buffer); // in rapidjson/writer.h doc.Accept(writer); psln(buffer.GetString()); }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- XML 与 JSON 优劣对比
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- VBA将excel数据表生成JSON文件
- newtonsoft.json解析天气数据出错解决方法
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- vbs 解析json jsonp的方法
- C++联合体转换成C#结构的实现方法
- Extjs4如何处理后台json数据中日期和时间
- C#实现将类的内容写成JSON格式字符串的方法
- JQuery ajax返回JSON时的处理方式 (三种方式)
- jquery JSON的解析方式示例介绍
- c#版json数据解析示例分享
- ASP JSON类文件的使用方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题