阅读量:3
jsoncpp 是一个 C++ 库,用于处理 JSON 数据
- 安装 jsoncpp:
首先,你需要从 jsoncpp 的 GitHub 仓库下载源代码,然后编译安装。下载地址:https://github.com/open-source-parsers/jsoncpp
- 编写一个简单的程序,用于解析 JSON 字符串:
#include
#include
int main() {
std::string json_str = R"({"name": "John", "age": 30, "city": "New York"})";
Json::Value root;
Json::CharReaderBuilder builder;
JSONCPP_STRING errs;
std::unique_ptr reader(builder.newCharReader()) ;
if (!reader->parse(json_str.c_str(), json_str.c_str() + json_str.size(), &root, &errs)) {
std::cerr << "Failed to parse JSON: " << errs << std::endl;
return 1;
}
std::cout << "Name: " << root["name"].asString() << std::endl;
std::cout << "Age: " << root["age"].asInt() << std::endl;
std::cout << "City: " << root["city"].asString() << std::endl;
return 0;
}
- 编译并运行程序:
g++ -o jsoncpp_example jsoncpp_example.cpp -ljsoncpp
./jsoncpp_example
输出结果:
Name: John
Age: 30
City: New York
- 使用 jsoncpp 读取 JSON 文件:
#include
#include
#include
int main() {
std::ifstream file("data.json");
if (!file.is_open()) {
std::cerr << "Failed to open file" << std::endl;
return 1;
}
std::string json_str((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
Json::Value root;
Json::CharReaderBuilder builder;
JSONCPP_STRING errs;
std::unique_ptr reader(builder.newCharReader()) ;
if (!reader->parse(json_str.c_str(), json_str.c_str() + json_str.size(), &root, &errs)) {
std::cerr << "Failed to parse JSON: " << errs << std::endl;
return 1;
}
std::cout << "Name: " << root["name"].asString() << std::endl;
std::cout << "Age: " << root["age"].asInt() << std::endl;
std::cout << "City: " << root["city"].asString() << std::endl;
return 0;
}
在这个例子中,我们从一个名为 data.json 的文件中读取 JSON 数据,然后使用 jsoncpp 解析并输出相关信息。
这些示例展示了如何使用 jsoncpp 库进行基本的 JSON 解析和操作。你可以根据自己的需求编写更复杂的程序来处理 JSON 数据。
以上就是关于“linux jsoncpp有啥使用案例”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm