在C++中处理JSON:面向初学者的解析与序列化

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在C++中处理JSON简介

JSON(JavaScript对象表示法)是一种轻量级的数据交换格式,广泛应用于Web开发、配置文件和API。尽管C++没有内置的JSON支持,但有许多库可以轻松便捷地处理这种格式。在本文中,我们将探讨如何使用流行的nlohmann/json库在C++中解析和序列化JSON数据。本材料面向已经熟悉C++基础的初学者开发者。



1. 安装并引入nlohmann/json库

nlohmann/json库是C++中最流行且易于使用的JSON处理库之一。它支持C++11及以上版本,并可在所有主流平台上运行。

安装方式

  • 下载头文件:前往GitHub仓库下载json.hpp文件。
  • 通过vcpkg安装:vcpkg install nlohmann-json
  • 通过Conan安装:conan install nlohmann_json/3.11.2@

安装后,只需在项目中引入该文件:

#include <iostream>#include "json.hpp"using json = nlohmann::json;

int main() { std::cout << "库已成功引入!" << std::endl; return 0;}


2. 解析JSON:从字符串和文件中读取数据

解析JSON是将JSON格式的字符串转换为C++数据结构的过程。nlohmann/json库使这一过程变得非常简单。



从字符串解析

我们来看一个解析简单JSON对象的示例:

#include <iostream>#include "json.hpp"using json = nlohmann::json;

int main() { std::string json_str = R"({ "name": "安娜", "age": 25, "is_student": false, "hobbies": ["阅读", "游泳", "编程"] })";

// 解析字符串 json data = json::parse(json_str);

// 访问数据 std::string name = data["name"]; int age = data["age"]; bool is_student = data["is_student"]; std::vector<std::string> hobbies = data["hobbies"];

std::cout << "姓名: " << name << std::endl; std::cout << "年龄: " << age << std::endl; std::cout << "学生: " << (is_student ? "是" : "否") << std::endl; std::cout << "爱好: "; for (const auto& hobby : hobbies) { std::cout << hobby << " "; } std::cout << std::endl;

return 0;}


从文件解析

JSON数据通常存储在文件中。以下是读取方法:

#include <iostream>#include <fstream>#include "json.hpp"using json = nlohmann::json;

int main() { std::ifstream file("data.json"); if (!file.is_open()) { std::cerr << "文件打开失败!" << std::endl; return 1; }

json data = json::parse(file); file.close();

// 输出数据 std::cout << "文件中的数据: " << data.dump(4) << std::endl; return 0;}

dump(4)方法将JSON转换回字符串,并缩进4个空格以便于阅读。



3. 序列化:从C++数据创建JSON

序列化是反向过程:将C++数据转换为JSON字符串。该库允许以直观的方式创建JSON对象。



创建简单的JSON对象

#include <iostream>#include "json.hpp"using json = nlohmann::json;

int main() { json person;

person["name"] = "伊万";

博客

书籍推荐