由于标准 C++ 库未提供原生的 JSON 处理能力,第三方库成为 C++ 解析和生成 JSON 数据的核心选择。RapidJSON 和 nlohmann/json 是两款主流的 C++ JSON 库 —— 前者以高性能著称,后者凭借简洁的语法和 STL 适配性广受青睐。掌握这两款库的下载方式、集成方法及核心使用场景(解析 / 生成 JSON),能让 C++ 程序高效处理 JSON 数据,适配各类跨语言数据交互需求。接下来,我们将详细讲解这两款库的具体使用示例。
RapidJSON 是一个快速的 C++ JSON 解析/生成库,它提供了一种方便的方式来解析和生成 JSON 数据。
下载RapidJSON 库:aly.cavidaga.com
代码语言:Bash
git clone https://github.com/Tencent/rapidjson.git
或者通过直接下载 zip 压缩文件方式:
代码语言:Bash
wget https://github.com/Tencent/rapidjson/archive/master.zip
unzip master.zip
RapidJSON 是一个头文件库,因此不需要编译和安装过程。只需将 RapidJSON 的头文件复制到项目中,并添加头文件路径到 C++ 编译器的 include 目录。
代码语言:C++
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
// JSON 字符串
const char* jsonString = "{\"name\": \"Lion\", \"age\": 30}";
// 解析 JSON
rapidjson::Document document;
document.Parse(jsonString);
// 读取解析后的数据
std::string name = document["name"].GetString();
int age = document["age"].GetInt();
代码语言:C++
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
// 创建 JSON 对象
rapidjson::Document document;
document.SetObject();
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
// 添加数据
rapidjson::Value name;
name.SetString("Lion");
document.AddMember("name", name, allocator);
rapidjson::Value age;
age.SetInt(30);
document.AddMember("age", age, allocator);
// 生成 JSON 字符串
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::string jsonString = buffer.GetString();
nlohmann/json 是一个现代 C++ 库,提供了便捷的 JSON 解析/生成功能,并支持 STL 类型的互操作。
下载 nlohmann/json 库:
代码语言:Bash
git clone https://github.com/nlohmann/json.git
或者通过直接下载 zip 压缩文件方式:
代码语言:Bash
wget https://github.com/nlohmann/json/archive/refs/heads/develop.zip
unzip develop.zip
nlohmann/json 是一个单头文件库(即仅有一个头文件),因此不需要编译和安装过程。
代码语言:C++
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// JSON 字符串
std::string jsonString = "{\"name\": \"Lion\", \"age\": 30}";
// 解析 JSON
json jsonObject = json::parse(jsonString);
// 读取解析后的数据
std::string name = jsonObject["name"];
int age = jsonObject["age"];
代码语言:C++
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// 创建 JSON 对象
json jsonObject;
// 添加数据
jsonObject["name"] = "Lion";
jsonObject["age"] = 30;
// 生成 JSON 字符串
std::string jsonString = jsonObject.dump();
RapidJSON 和 nlohmann/json 作为 C++ 处理 JSON 的主流第三方库,分别适配了 “高性能” 和 “易用性” 的不同需求 ——RapidJSON 凭借轻量级头文件设计和高效解析 / 生成能力,适合性能敏感场景;nlohmann/json 则以接近原生 STL 的语法,降低了 JSON 处理的学习和使用成本。两款库均无需编译安装,集成便捷,掌握它们的下载与核心使用方法,能让 C++ 程序轻松实现 JSON 数据的解析与生成,满足跨语言数据交互的开发需求。
正在加载... ...