您好,登录后才能下订单哦!
在 Linux 下,有许多 C++ 库可以用来解析 JSON 数据
nlohmann/json 是一个广泛使用的 C++ JSON 库,它的 GitHub 仓库地址为:https://github.com/nlohmann/json
要使用这个库,首先需要将其添加到你的项目中。如果你使用的是 CMake,可以在你的 CMakeLists.txt
文件中添加以下代码:
add_subdirectory(nlohmann-json)
include_directories(${nlohmann_json_SOURCE_DIR}/include)
然后,你可以在你的 C++ 文件中包含 nlohmann/json.hpp
头文件并使用它来解析 JSON 数据:
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;
int main() {
string json_str = R"(
{
"name": "John",
"age": 30,
"city": "New York"
}
)"_json; // 注意 _json 后缀
json j = json::parse(json_str);
cout << "Name: " << j["name"] << endl;
cout << "Age: " << j["age"] << endl;
cout << "City: " << j["city"] << endl;
return 0;
}
rapidjson 是一个高性能的 C++ JSON 库,它的 GitHub 仓库地址为:https://github.com/Tencent/rapidjson
要使用这个库,首先需要将其添加到你的项目中。如果你使用的是 CMake,可以在你的 CMakeLists.txt
文件中添加以下代码:
add_subdirectory(rapidjson)
include_directories(${RapidJSON_SOURCE_DIR}/include)
然后,你可以在你的 C++ 文件中包含 rapidjson/document.h
头文件并使用它来解析 JSON 数据:
#include <iostream>
#include <rapidjson/document.h>
using namespace rapidjson;
using namespace std;
int main() {
const char* json_str = R"(
{
"name": "John",
"age": 30,
"city": "New York"
}
)";
Document d;
d.Parse(json_str);
cout << "Name: " << d["name"].GetString() << endl;
cout << "Age: " << d["age"].GetInt() << endl;
cout << "City: " << d["city"].GetString() << endl;
return 0;
}
这两个库都有很好的文档和社区支持,你可以根据自己的需求选择合适的库来解析 JSON 数据。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。