配置安装以及使用范例
一:配置安装
简介:RapidJSON 是一个 C++ 的 JSON 解析器及生成器。国内科技巨头腾讯开源的C++第三方库,其性能高效,并具有极大的兼容性(跨平台)。
下载:https://github.com/Tencent/rapidjson
官方使用手册:http://rapidjson.org/zh-cn/(中文版)
相关配置安装可参考另一篇博文C++开源库使用之evpp(一)(https://blog.csdn.net/qingfengleerge/article/details/82995339)。
如果不使用上述方式配置安装,在项目中只需要将 include/rapidjson
目录复制至系统或项目的 include 目录中。
二:使用范例
范例一:解析json串
#include <iostream>
#include <string>
#include <cassert>
//RapidJSON库(第三方库)
#include <rapidjson/document.h>
using namespace rapidjson;
int main()
{
const char* test_string= "{ \"MessageName\": \"EnterLookBackFlightMode\",\"MessageBody\" : {\"ZoneServer\": \"西南区\",\"Airport\" : \"双流机场\",\"Longitude\" : 104.24647,\"Latitude\" : 30.80301,\"Radius\" : 300,\"Call\" : \"CES5491\",\"StartTime\" : \"2018-12-19 17:15:34.545\",\"EndTime\" : \"2018-12-19 19:15:34.545\",\"ClientInfos\" :[{\"IP\": \"192.168.1.10\",\"Port\" : \"888\"},{\"IP\": \"192.168.1.11\",\"Port\" : \"888\"}]}}";
Document document;
document.Parse(test_string);
assert(document.IsObject());
std::cout<<document.HasMember("MessageBody")<<std::endl;
const Value& message_body=document["MessageBody"];
std::cout<<message_body.IsObject()<<std::endl;
std::cout<<message_body.HasMember("call")<<std::endl;
std::string hang_ban=message_body["Call"].GetString();
std::cout<<hang_ban<<std::endl;
return 0;
}
范例二:生成json串
#include <iostream>
#include <string>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
using namespace rapidjson;
int main()
{
//官方示例
const char* json="{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
//利用DOM作出修改
Value& s=d["stars"];
s.SetInt(s.GetInt()+1);
//把DOM转换为JSON
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
//输出
std::cout<<buffer.GetString()<<std::endl;
//自定义示例
Document document;
document.SetObject();
Document::AllocatorType& allocator=document.GetAllocator();
std::string str("I love you!");
document.AddMember("id",1,allocator);
document.AddMember("port",888,allocator);
document.AddMember("curry",StringRef(str.c_str()),allocator);
Value time_of_day_objects(kObjectType);
std::string time_str="2019-01-04 10:31:35.256";
time_of_day_objects.AddMember("TOD",StringRef(time_str.c_str()),allocator);
document.AddMember("TimeOfDay",time_of_day_objects,allocator);
StringBuffer custom_buffer;
Writer<StringBuffer> custom_writer(custom_buffer);
document.Accept(custom_writer);
const std::string custom_json=custom_buffer.GetString();
std::cout<<custom_json<<std::endl;
}
输出: