C++中解析JSON需借助第三方库,常用的是jsoncpp和nlohmann/json。1. jsoncpp轻量跨平台,通过Json::Reader解析字符串,需安装libjsoncpp-dev并链接-ljsoncpp;示例代码展示从JSON字符串提取name、age、city字段。2. nlohmann/json为单头文件库,支持现代C++语法,只需包含json.hpp即可使用,通过json::parse()解析,支持异常处理;示例包括解析基本类型及数组(如hobbies)。3. 对嵌套结构(如user.profile.name),nlohmann/json可通过链式下标访问,代码简洁。4. 推荐:传统项目用jsoncpp,现代C++项目优选nlohmann/json,性能敏感场景可选rapidjson。解析前应验证JSON格式,并使用try-catch捕获异常,确保健壮性。

在C++中解析JSON字符串,由于标准库不直接支持JSON操作,通常需要借助第三方库来完成。目前最常用且易于使用的库是 jsoncpp 和 nlohmann/json(也称JSON for Modern C++)。下面分别介绍这两种方法,并提供具体示例。
jsoncpp 是一个轻量级、跨平台的C++库,专门用于处理JSON数据。它提供了简单的API来解析和生成JSON。
安装 jsoncpp(Ubuntu/Debian):
sudo apt-get install libjsoncpp-dev
编译时链接库:
立即学习“C++免费学习笔记(深入)”;
g++ main.cpp -ljsoncpp -o parse_json
示例代码:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
#include <iostream>
#include <json/json.h>
#include <sstream>
int main() {
std::string json_str = R"({"name": "Alice", "age": 25, "city": "Beijing"})";
Json::Value root;
Json::Reader reader;
std::istringstream iss(json_str);
bool parsingSuccessful = reader.parse(iss, root);
if (!parsingSuccessful) {
std::cout << "Failed to parse JSON: " << reader.getFormattedErrorMessages();
return 1;
}
std::string name = root["name"].asString();
int age = root["age"].asInt();
std::string city = root["city"].asString();
std::cout << "Name: " << name << "\n";
std::cout << "Age: " << age << "\n";
std::cout << "City: " << city << "\n";
return 0;
}
nlohmann/json 是一个单头文件库,使用现代C++语法,接口简洁直观,广泛用于C++11及以上项目。
获取方式:
single_include/nlohmann/json.hpp 添加到项目中即可使用示例代码:
#include <iostream>
#include <string>
#include "json.hpp"
using json = nlohmann::json;
int main() {
std::string json_str = R"({"name": "Bob", "age": 30, "hobbies": ["reading", "coding"]})";
try {
json j = json::parse(json_str);
std::string name = j["name"];
int age = j["age"];
auto hobbies = j["hobbies"];
std::cout << "Name: " << name << "\n";
std::cout << "Age: " << age << "\n";
std::cout << "Hobbies: ";
for (const auto& h : hobbies) {
std::cout << h << " ";
}
std::cout << "\n";
} catch (const std::exception& e) {
std::cerr << "JSON parse error: " << e.what() << "\n";
}
return 0;
}
对于包含对象或数组嵌套的复杂结构,两种库都能轻松应对。
使用 nlohmann/json 处理嵌套对象:
std::string complex_json = R"({
"user": {
"id": 1001,
"profile": {
"name": "Charlie",
"email": "charlie@example.com"
}
},
"active": true
})";
json j = json::parse(complex_json);
std::string name = j["user"]["profile"]["name"];
int user_id = j["user"]["id"];
bool active = j["active"];
std::cout << "User: " << name << ", ID: " << user_id << ", Active: " << active << "\n";
以上就是c++++中如何解析JSON字符串_c++ JSON解析方法与示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号