C++中的JSON处理:库、解析与示例
JSON(JavaScript Object Notation)是最流行的数据交换格式之一。尽管C++没有内置对JSON的支持,但有多个强大的库可以轻松解析、生成和修改JSON数据。本文将介绍三个主要库:nlohmann/json、RapidJSON和Boost.PropertyTree,并提供实际使用示例。
为什么C++需要JSON库?
C++是一种面向性能的编译型语言。使用正则表达式或字符串操作手动解析JSON是一项繁琐且容易出错的任务。专门的库提供了:
- 高速解析和序列化。
- 直观的API(通常采用STL风格)。
- 对JSON标准的支持(包括嵌套对象、数组、null、Unicode)。
- 最少的依赖项(通常是header-only)。
1. nlohmann/json库(现代C++的JSON)
最流行且易于使用的库。以header-only(单个头文件)形式分发。非常适合教育项目和小型应用。
安装
从仓库nlohmann/json下载文件json.hpp并包含它:
#include "json.hpp"using json = nlohmann::json;示例:从字符串解析JSON
#include <iostream>#include "json.hpp"
int main() { std::string json_str = R"({ "name": "PythonLib", "year": 2025, "tags": ["C++", "JSON", "education"], "active": true })";
json data = json::parse(json_str);
std::cout << "Name: " << data["name"] << ""; std::cout << "Year: " << data["year"] << ""; std::cout << "First tag: " << data["tags"][0] << ""; std::cout << "Active: " << data["active"] << "";
return 0;}示例:创建和序列化JSON
#include <iostream>#include "json.hpp"
int main() { json obj; obj["title"] = "JSON in C++"; obj["pages"] = 42; obj["chapters"] = {"intro", "basics", "advanced"}; obj["metadata"]["author"] = "PythonLib Team";
std::string serialized = obj.dump(4); // 4 — 缩进用于美观输出 std::cout << serialized << "";
return 0;}2. RapidJSON库
RapidJSON是一个高性能库,专注于速度和最小内存消耗。常用于游戏、服务器应用和嵌入式系统。支持SAX风格(流式解析)和DOM风格。
安装
从GitHub下载存档并包含头文件:
#include "rapidjson/document.h"#include "rapidjson/writer.h"#include "rapidjson/stringbuffer.h"示例:解析和读取
#include <iostream>#include "rapidjson/document.h"
int main() { const char* json = "{\\"project\\":\\"PythonLib\\",\\"version\\":2.0}"; rapidjson::Document doc; doc.Parse(json);
if (doc.HasParseError()) { std::cerr << "Parse error!"; return 1; }
std::cout << "Project: " << doc["project"].GetString() << ""; std::cout << "Version: " << doc["version"].GetDouble() << "";
return 0;}示例:生成JSON
#include <iostream>#include "rapidjson/docume