
解析 JSON 字符串在 C++ 中是一个常见需求,尤其是在处理网络请求、配置文件或前后端数据交互时。由于 C++ 标准库不直接支持 JSON 解析,通常需要借助第三方库来完成。下面介绍几种常用的 C++ JSON 解析库及其基本使用方法。
以下是几个广泛使用且维护良好的 C++ JSON 库:
这个库以简洁的语法著称,推荐用于现代 C++ 项目。
// 安装方式:通过 vcpkg、conan 或直接下载 single_include 版本使用步骤:
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <iostream>
#include <string>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
int main() {
std::string json_str = R"({
"name": "Tom",
"age": 25,
"is_student": false,
"hobbies": ["reading", "gaming"]
})";
try {
json j = json::parse(json_str);
std::cout << "Name: " << j["name"] << std::endl;
std::cout << "Age: " << j["age"] << std::endl;
std::cout << "Is student: " << std::boolalpha << j["is_student"] << std::endl;
for (const auto& hobby : j["hobbies"]) {
std::cout << "Hobby: " << hobby << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "JSON parse error: " << e.what() << std::endl;
}
return 0;
}
编译时确保启用 C++11 或更高标准:
g++ -std=c++11 main.cpp -o main
JsonCpp 是较早出现的库,API 稍显传统但稳定。
示例代码:
#include <iostream>
#include <string>
#include <json/json.h>
int main() {
std::string json_str = R"({
"name": "Alice",
"score": 95.5
})";
Json::Value root;
Json::CharReaderBuilder builder;
std::string errs;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if (!reader->parse(json_str.c_str(), json_str.c_str() + json_str.size(), &root, &errs)) {
std::cerr << "Parse error: " << errs << std::endl;
return -1;
}
std::cout << "Name: " << root["name"].asString() << std::endl;
std::cout << "Score: " << root["score"].asDouble() << std::endl;
return 0;
}
编译命令(需链接 JsonCpp 库):
g++ main.cpp -ljsoncpp -o main
rapidjson 以高性能和零依赖著称,适合嵌入式或性能关键系统。
示例代码:
#include <iostream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main() {
std::string json_str = R"({"user":"Bob","active":true})";
Document doc;
doc.Parse(json_str.c_str());
if (doc.HasParseError()) {
std::cerr << "Parse error" << std::endl;
return -1;
}
if (doc.HasMember("user") && doc["user"].IsString()) {
std::cout << "User: " << doc["user"].GetString() << std::endl;
}
if (doc["active"].IsBool()) {
std::cout << "Active: " << (doc["active"].GetBool() ? "yes" : "no") << std::endl;
}
return 0;
}
基本上就这些。选择哪个库取决于你的项目需求:追求简洁用 nlohmann/json,追求性能用 rapidjson,需要兼容旧项目可用 JsonCpp。集成时注意异常处理和字符串合法性检查,避免运行时崩溃。不复杂但容易忽略。
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号