c++怎么解析JSON数据_c++ JSON数据解析示例

使用nlohmann/json库可高效解析json,需包含json.hpp头文件;示例展示了解析字符串、访问字段、遍历数组、处理嵌套对象及类型安全检查方法,并支持从文件读取数据。

c++怎么解析JSON数据_c++ JSON数据解析示例

c++中解析JSON数据,通常会借助第三方库来完成,因为标准C++库并不直接支持json处理。最常用且轻量高效的库是 nlohmann/json,它使用方便、头文件仅需包含一个头文件即可使用。

1. 引入nlohmann JSON库

这个库是单头文件库,使用非常简单:

– 下载地址: https://www.php.cn/link/b82e68e6366d4177332acdf3fa4d1e3a
– 将 json.hpp 头文件放入项目目录,然后包含即可

示例代码包含方式:

#include <iostream> #include <string> #include "json.hpp" <p>// 使用命名空间简化代码 using json = nlohmann::json; 

2. 解析JSON字符串示例

下面是一个解析JSON字符串的完整示例:

立即学习C++免费学习笔记(深入)”;

int main() {     // JSON字符串     std::string json_str = R"({         "name": "张三",         "age": 25,         "city": "北京",         "hobbies": ["读书", "游泳", "编程"],         "address": {             "street": "中关村大街",             "zipcode": "100086"         }     })"; <pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 解析JSON json j = json::parse(json_str);  // 获取基本字段 std::string name = j["name"]; int age = j["age"]; std::string city = j["city"];  std::cout << "姓名: " << name << std::endl; std::cout << "年龄: " << age << std::endl; std::cout << "城市: " << city << std::endl;  // 遍历数组 std::cout << "爱好: "; for (const auto& hobby : j["hobbies"]) {     std::cout << hobby << " "; } std::cout << std::endl;  // 访问嵌套对象 std::string street = j["address"]["street"]; std::string zipcode = j["address"]["zipcode"]; std::cout << "街道: " << street << std::endl; std::cout << "邮编: " << zipcode << std::endl;  return 0;

}

3. 安全访问与类型检查

实际开发中,JSON字段可能缺失或类型不符,建议做判断:

c++怎么解析JSON数据_c++ JSON数据解析示例

Find JSON Path Online

Easily find JSON paths within JSON objects using our intuitive Json Path Finder

c++怎么解析JSON数据_c++ JSON数据解析示例30

查看详情 c++怎么解析JSON数据_c++ JSON数据解析示例

if (j.contains("age") && j["age"].is_number()) {     int age = j["age"]; } else {     std::cout << "年龄字段缺失或类型错误" << std::endl; } 

也可以使用 at()value() 方法更安全地获取值:

// 使用 value 提供默认值 std::string gender = j.value("gender", "未知"); <p>// 使用 at 可捕获异常 try { std::string name = j.at("name"); } catch (json::exception& e) { std::cout << "访问字段出错: " << e.what() << std::endl; } 

4. 从文件读取JSON

如果JSON数据保存在文件中,可以这样读取:

#include <fstream> <p>std::ifstream file("data.json"); if (file.is_open()) { json j; file >> j;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::cout << "文件中的名字: " << j["name"] << std::endl;

}

基本上就这些。使用 nlohmann/json 库后,C++ 解析 JSON 就变得像脚本语言一样直观。只要注意字段存在性和类型判断,就能稳定运行。

上一篇
下一篇
text=ZqhQzanResources