C++使用rapidjson生成和解析JSON数据
update:2021-10-28
rapidjson是腾讯开源的C++ json库,开源地址看这里:https://github.com/Tencent/rapidjson

rapidjson无需编译,只要将include下的头文件复制到你工程中就可以直接使用了。

在你的cpp文件中引入头文件

include "include/rapidjson/document.h"

include "include/rapidjson/writer.h"

include "include/rapidjson/stringbuffer.h"

生成JSON

string sRobotId = "R201807280858001";
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
Document doc;
doc.SetObject();
Document::AllocatorType &allocator = doc.GetAllocator();
doc.AddMember("robotId", StringRef(sRobotId.c_str()), allocator);
doc.Accept(writer);
cout << buffer.GetString() << endl;
解析JSON

string cJson = "{"statusCode": 200,"data": {"text": "test"}}";
Document d;
d.Parse(cJson.c_str());
Value& s = d"data";
cout << s.GetString() << endl;
Referenced from:https://dev-tang.com/post/2018/07/rapidjson.html

本文链接地址:https://const.net.cn/537.html

标签: none

添加新评论