nlohmann/json库使C++处理JSON更高效,支持解析字符串、文件读写、生成格式化JSON,并提供类型检查与异常处理机制,集成简单且兼容C++11及以上版本。

在C++中处理JSON数据,由于标准库没有内置支持,通常需要借助第三方库来完成解析与生成。目前最常用且功能强大的库是 nlohmann/json(也称 JSON for Modern C++),它使用方便、头文件仅需包含一个文件,兼容C++11及以上版本。
该库以简洁的语法操作JSON,支持从字符串、文件中读取JSON,并访问其中的数据。
json.hpp 导入项目。解析JSON字符串:
#include <iostream>
#include <string>
#include "json.hpp"
using json = nlohmann::json;
int main() {
    std::string json_str = R"({
        "name": "Alice",
        "age": 25,
        "is_student": false,
        "hobbies": ["reading", "coding"]
    })";
    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;
    }
    return 0;
}
使用该库可以轻松构建复杂的JSON结构并输出为字符串。
立即学习“C++免费学习笔记(深入)”;
创建并序列化JSON:
json j;
j["name"] = "Bob";
j["age"] = 30;
j["is_student"] = true;
j["skills"] = {"C++", "Python", "JavaScript"};
std::string output = j.dump(4); // 格式化缩进4个空格
std::cout << output << std::endl;
输出结果:
 
                        Easily find JSON paths within JSON objects using our intuitive Json Path Finder
 30
30
                             
                    {
    "age": 30,
    "is_student": true,
    "name": "Bob",
    "skills": ["C++", "Python", "JavaScript"]
}
结合标准文件流操作,可实现持久化存储。
读取JSON文件:
#include <fstream>
std::ifstream file("data.json");
if (file.is_open()) {
    json j;
    file >> j;
    std::cout << "Loaded: " << j.dump(2) << std::endl;
}
写入JSON到文件:
std::ofstream o("output.json");
o << std::setw(4) << j << std::endl; // 需包含 <iomanip> 控制格式
访问JSON字段前建议检查是否存在及类型是否正确,避免运行时异常。
if (j.contains("age") && j["age"].is_number()) {
    int age = j["age"];
} else {
    std::cerr << "Invalid or missing 'age'" << std::endl;
}
// 或使用 try-catch
try {
    auto name = j.at("name"); // 使用 at 会抛出异常如果键不存在
} catch (json::exception& e) {
    std::cerr << "JSON error: " << e.what() << std::endl;
}
基本上就这些。nlohmann/json 让C++处理JSON变得直观高效,适合大多数项目需求。集成简单,文档完善,是现代C++开发中的首选方案。
以上就是c++++怎么处理json数据_C++解析与生成JSON数据的方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号