答案是使用nlohmann/json库解析JSON。1. 引入json.hpp头文件;2. 用std::ifstream读取文件;3. 通过nlohmann::json::parse解析内容,捕获异常处理错误。

在C++中解析和生成JSON数据,由于标准库不直接支持JSON操作,通常需要借助第三方库来完成。目前最常用且易于使用的库是 nlohmann/json(也叫 JSON for Modern C++)。它使用简单、头文件-only,无需编译,非常适合中小型项目。
这个库是 header-only 的,意味着你只需要下载一个头文件并包含即可使用。
步骤:以下是一个读取本地 JSON 文件并解析内容的示例:
#include <iostream>
#include <fstream>
#include <string>
#include "json.hpp"
// 使用命名空间简化代码
using json = nlohmann::json;
int main() {
    // 打开 JSON 文件
    std::ifstream file("data.json");
    if (!file.is_open()) {
        std::cerr << "无法打开文件!" << std::endl;
        return -1;
    }
    // 解析 JSON 数据
    json j;
    try {
        file >> j;
    } catch (const std::exception& e) {
        std::cerr << "JSON 解析失败:" << e.what() << std::endl;
        return -1;
    }
    // 访问数据(假设 JSON 是对象)
    std::string name = j["name"];
    int age = j["age"];
    std::vector<std::string> hobbies = j["hobbies"];
    std::cout << "姓名: " << name << "\n";
    std::cout << "年龄: " << age << "\n";
    std::cout << "爱好: ";
    for (const auto& h : hobbies) {
        std::cout << h << " ";
    }
    std::cout << "\n";
    return 0;
}
file >> j 自动将文件内容解析为 JSON 对象你也可以用代码构造 JSON 对象,并写入文件:
立即学习“C++免费学习笔记(深入)”;
 
                        Easily find JSON paths within JSON objects using our intuitive Json Path Finder
 30
30
                             
                    json j;
j["name"] = "张三";
j["age"] = 25;
j["is_student"] = false;
j["hobbies"] = {"读书", "游泳", "编程"};
// 输出为字符串(带缩进)
std::string output = j.dump(4);  // 参数 4 表示缩进空格数
std::cout << output << std::endl;
// 写入文件
std::ofstream out("output.json");
out << j.dump(2);
out.close();
JSON 经常包含嵌套结构,nlohmann/json 支持链式访问:
json config;
std::ifstream cfg_file("config.json") >> config;
// 假设 JSON 中有:{"server": {"host": "127.0.0.1", "port": 8080}}
std::string host = config["server"]["host"];
int port = config["server"]["port"];
// 遍历数组对象
for (auto& user : config["users"]) {
    std::cout << "用户: " << user["name"] << ", ID: " << user["id"] << "\n";
}
该库还支持 STL 风格的迭代、自定义类型序列化等高级功能。
基本上就这些。只要引入 nlohmann/json,C++ 处理 JSON 就变得非常直观和安全。推荐用于大多数现代 C++ 项目(需支持 C++11 及以上)。
以上就是c++++怎么解析JSON文件_c++ JSON数据解析与序列化方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号