本文将围绕 Linux C/C++ 最快的 JSON 库 —— RapidJSON
,从多个维度展开详细介绍,包括:
在选择 JSON 库时,我们通常关注以下几个维度:
库名 | 语言 | 性能 | 特点 | 备注 |
---|---|---|---|---|
RapidJSON | C++ | 极高 | 无依赖、DOM/SAX 双模式、零拷贝 | 适合追求极致性能场景 |
nlohmann/json | C++ | 中等偏上 | 类似 STL 使用体验,现代 C++ 风格 | 使用简单,性能非极致 |
Jansson | C | 中等 | 纯 C 接口、使用简洁 | 适合 C 项目,接口朴素 |
cJSON | C | 较快 | 小巧轻量、易于嵌入 | 嵌入式项目优选 |
JSON-C | C | 一般 | 线程安全、广泛应用于 Linux 系统 | 接口不够现代,性能较低 |
从上表可以看出,RapidJSON 是性能最强的 JSON 库之一,尤其适用于对速度和内存控制要求较高的系统开发场景。
git clone https://github.com/Tencent/rapidjson.git
将 include/rapidjson
目录拷贝到项目路径下,在源码中引用:
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
include_directories(${PROJECT_SOURCE_DIR}/third_party/rapidjson/include)
RapidJSON 是 header-only 库,不需要编译静态库或动态库。
#include "rapidjson/document.h"
#include
using namespace rapidjson;
int main() {
const char* json = "{\"name\":\"Linux\",\"year\":2025}";
Document d;
d.Parse(json);
if (d.HasParseError()) {
std::cerr << "Parse error!\n";
return -1;
}
std::cout << "name: " << d["name"].GetString() << "\n";
std::cout << "year: " << d["year"].GetInt() << "\n";
return 0;
}
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include
using namespace rapidjson;
int main() {
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
d.AddMember("project", "RapidJSON", allocator);
d.AddMember("stars", 9000, allocator);
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
std::cout << buffer.GetString() << std::endl;
return 0;
}
const char* json = "[1, 2, 3, 4, 5]";
Document d;
d.Parse(json);
for (auto& v : d.GetArray()) {
std::cout << v.GetInt() << " ";
}
d["stars"].SetInt(10000); // 替换原字段数值
库名 | 解析 | 生成 | 总耗时 |
---|---|---|---|
RapidJSON | 11ms | 8ms | 19ms |
cJSON | 24ms | 13ms | 37ms |
Jansson | 27ms | 16ms | 43ms |
nlohmann/json | 35ms | 20ms | 55ms |
JSON-C | 41ms | 22ms | 63ms |
RapidJSON 的性能表现明显优于其他库,尤其在解析与生成两方面均表现出色。
在嵌入式项目中,通常需要从 JSON 配置文件读取参数并构建结构体,RapidJSON 可高效实现如下功能:
struct Config {
std::string device;
int baudrate;
};
Config load_config(const std::string& path) {
std::ifstream ifs(path);
std::stringstream ss;
ss << ifs.rdbuf();
Document d;
d.Parse(ss.str().c_str());
Config cfg;
cfg.device = d["device"].GetString();
cfg.baudrate = d["baudrate"].GetInt();
return cfg;
}
GetString()
前需确保字段存在且类型正确在多模块系统中,可能存在部分使用 cJSON
,部分使用 RapidJSON
的情况。此时建议使用统一封装接口,或进行字符串中转:
std::string convert(const cJSON* cj) {
char* raw = cJSON_PrintUnformatted(cj);
std::string json(raw);
cJSON_free(raw);
return json;
}
然后再用 RapidJSON 接口解析字符串。
RapidJSON 是当前 Linux C/C++ 平台上性能最强的 JSON 库之一,适用于系统级软件、嵌入式、网络通信、日志分析等高性能场景。其零依赖、DOM/SAX 双支持架构,加上丰富的接口与优雅的设计,使其在项目开发中具备极高的实用价值。
对于追求编解码速度和内存效率的开发者而言,RapidJSON 是不二之选。
推荐搭配 Valgrind 或 AddressSanitizer 使用,确保 JSON 操作无内存问题。