阅读量:81
在C++中高效处理JSON数据,可以使用一些流行的JSON库,如RapidJSON、nlohmann/json等
-
首先,需要安装RapidJSON库。你可以从GitHub上下载源代码:https://github.com/Tencent/rapidjson
-
将下载的源代码解压并将
include文件夹添加到项目的头文件搜索路径中。 -
接下来,我们将使用RapidJSON库来解析和生成JSON数据。
示例1:解析JSON字符串
#include
#include
#include "rapidjson/document.h"
int main() {
std::string json_str = R"({"name": "John", "age": 30, "city": "New York"})";
rapidjson::Document document;
if (document.Parse(json_str.c_str()).HasParseError()) {
std::cerr << "Error parsing JSON string."<< std class="hljs-keyword">return 1;
}
std::string name = document["name"].GetString();
int age = document["age"].GetInt();
std::string city = document["city"].GetString();
std::cout << "Name: "<< name class="hljs-string">", Age: "<< age class="hljs-string">", City: "<< city class="hljs-keyword">return 0;
}
示例2:生成JSON字符串
#include
#include
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
int main() {
rapidjson::Document document;
document.SetObject();
document.AddMember("name", "John", document.GetAllocator());
document.AddMember("age", 30, document.GetAllocator());
document.AddMember("city", "New York", document.GetAllocator());
rapidjson::StringBuffer buffer;
rapidjson::Writer writer(buffer) ;
document.Accept(writer);
std::string json_str = buffer.GetString();
std::cout << "Generated JSON string: "<< json class="hljs-keyword">return 0;
}
这些示例展示了如何使用RapidJSON库在C++中解析和生成JSON数据。当然,还有其他JSON库可供选择,但RapidJSON是一个非常流行且性能良好的库。在处理大量JSON数据时,请确保选择适合你项目需求的库。