一、JSON基础与解析流程
1.1 JSON数据结构
JSON包含两种核心结构():
- 对象:
{}
包裹的键值对集合 - 数组:
[]
包裹的值序列
1.2 解析流程
flowchart TD
A[加载JSON数据] --> B{数据来源}
B -->|字符串| C[直接解析]
B -->|文件| D[读取后解析]
C/D --> E[构建DOM树]
E --> F[遍历节点]
F --> G[类型检查与数据提取]
G --> H[错误处理]
二、主流JSON库详解
2.1 nlohmann/json库
2.1.1 基础用法
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// 解析字符串
std::string jsonStr = R"({"name":"John","age":30})";
json j = json::parse(jsonStr); //
// 访问数据
std::string name = j["name"];
int age = j["age"];
// 序列化
std::string output = j.dump(4); // 缩进4空格
2.1.2 嵌套结构处理
flowchart TD
A[解析JSON对象] --> B[检查键存在性]
B -->|存在| C[获取子对象]
B -->|不存在| D[抛出异常]
C --> E{是否为数组}
E -->|是| F[遍历数组元素]
E -->|否| G[继续解析对象]
2.2 RapidJSON库
2.2.1 高性能解析
#include "rapidjson/document.h"
const char* json = R"({"sensor": {"temp": 23.5, "active": true}})";
rapidjson::Document d;
d.Parse(json); //
// 访问数据
if(d.HasMember("sensor")) {
const rapidjson::Value& sensor = d["sensor"];
double temp = sensor["temp"].GetDouble();
bool active = sensor["active"].GetBool();
}
2.2.2 SAX解析模式
flowchart LR
A[输入流] --> B[SAX解析器]
B --> C{事件类型}
C -->|StartObject| D[创建新对象]
C -->|Key| E[记录当前键]
C -->|Value| F[存储键值对]
C -->|EndObject| G[完成对象构建]
三、关键技术点实现
3.1 类型安全访问
// nlohmann类型检查
if(j.at("price").is_number_float()) {
float price = j["price"];
}
// RapidJSON类型断言
if(d["status"].IsString()) {
std::string status = d["status"].GetString();
}
3.2 错误处理机制
try {
json j = json::parse(invalidJson);
} catch (json::parse_error& e) {
std::cerr << "解析错误: " << e.what()
<< " at byte " << e.byte << endl;
}
// RapidJSON错误码检查
if(d.HasParseError()) {
std::cout << "Error offset: " << d.GetErrorOffset()
<< " Reason: " << rapidjson::GetParseError_En(d.GetParseError());
}
四、技术对比与选型
特性 | nlohmann/json | RapidJSON | jsoncpp |
---|---|---|---|
API友好度 | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐ |
解析性能 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐ |
内存占用 | 较高 | 低 | 中等 |
C++标准支持 | C++11+ | C++03+ | C++98+ |
文档完整性 | 优秀 | 良好 | 一般 |
五、扩展应用示例
5.1 配置解析器
class ConfigParser {
public:
void load(const std::string& path) {
std::ifstream f(path);
_config = json::parse(f);
}
template<typename T>
T get(const std::string& key) {
return _config[key].get<T>();
}
private:
json _config;
};
5.2 数据序列化流程
sequenceDiagram
participant App as 应用程序
participant Lib as JSON库
participant FS as 文件系统
App->>Lib: 创建JSON对象
Lib->>App: 返回空对象
App->>Lib: 添加键值对
App->>Lib: 调用dump()
Lib->>FS: 写入格式化字符串
FS->>App: 返回写入结果
完整代码示例与流程图生成工具可参考CSDN文库(搜索编号20240604、20241222)获取实现细节。建议结合VSCode的Mermaid插件实时预览流程图效果。
https://github.com/0voice