rapidjson 简单使用
发布时间:2020-12-16 18:42:50 所属栏目:百科 来源:网络整理
导读:rapidjson 相较于 jsoncpp 最方便的一点就在于在c++ 项目中只需要包含rapidjson 的头文件就能使用,而jsoncpp 需要使用相同平台下编译出来的lib文件进行使用,用起来没有rapidjson 方便。 ? 通过开源作者的说明,rapidjson 速度快,性能可与strlen() 相比。
rapidjson 相较于 jsoncpp 最方便的一点就在于在c++ 项目中只需要包含rapidjson 的头文件就能使用,而jsoncpp 需要使用相同平台下编译出来的lib文件进行使用,用起来没有rapidjson 方便。 ? 通过开源作者的说明,rapidjson 速度快,性能可与strlen() 相比。 以下是一些关于rapidjson 的简单用法: 使用之前只需要将对应的头文件包含进来 #include "include/rapidjson/document.h" #include "include/rapidjson/writer.h" #include "include/rapidjson/stringbuffer.h" using namespace rapidjson; 读取一个json 字符串对象数组。 //其中包含简单的字符对象,对象数组 const char* str = "{"uploadid": "UP000000","code": [{"code":100}],"msg": "study","files": ""}"; Document d; d.Parse(str); Value& s = d["code"]; assert(s.IsArray()); Value &v = s[0]; assert(v.IsObject()); int n = v["code"].GetInt(); StringBuffer buffer; Writer<StringBuffer> writer(buffer); //将json 中的数据转换成字符串形式 d.Accept(writer); cout << buffer.GetString() << endl; 组装一个json 字符串 Document d; Document::AllocatorType &allocator = d.GetAllocator(); //索引器 d.SetObject(); //创建一个对象在DOM下 Value ItemTmp(kArrayType); //创建一个数组元素 //插入一个string 类型对象 Value obj(kObjectType); Value strValue; strValue.SetString(str,allocator); //插入一个double 类型对象 Value Tmp; Tmp.SetDouble(ask); obj.AddMember("ask_price",Tmp,allocator); /* ................................................ */ ItemTmp.PushBack(obj,allocator); //将这个对象数组插入到DOM数组中去 d.AddMember("data",ItemTmp,allocator); //这个对象数组在data这个对象下 //将json对象转换成string类型输出 StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); std::string strData = buffer.GetString(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |