配置安裝以及使用範例
一:配置安裝
簡介: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;
}
輸出: