通八洲科技

C++如何解析JSON数据?(nlohmann/json库示例)

日期:2026-01-01 00:00 / 作者:冰火之心
nlohmann/json解析JSON直观高效:通过json::parse()转换字符串,支持自动类型转换;用[]访问字段、at()安全获取、value()设默认值;数组遍历用范围for循环。

用 nlohmann/json 解析 JSON 数据在 C++ 中非常直观,核心是把 JSON 字符串转为 json 类型对象,再通过键名或下标访问字段。

安装与引入

nlohmann/json 是 header-only 库,无需编译。下载 single include 文件(如 json.hpp),放入项目目录后直接包含:

#include "json.hpp"
using json = nlohmann::json;

解析字符串并读取基本字段

调用 json::parse() 将字符串转为 JSON 对象,支持自动识别对象(object)、数组(array)、字符串、数字等类型:

std::string json_str = R"({"name":"Alice","age":30,"active":true})";
json j = json::parse(json_str);
std::string name = j["name"]; // 自动转 string
int age = j["age"]; // 自动转 int
bool active = j["active"]; // 自动转 bool

安全访问嵌套结构与数组

使用 at() 可捕获不存在字段的异常;用 value() 提供默认值避免崩溃;数组用方括号加索引访问:

反序列化为自定义结构体

通过重载 from_json 函数,可将 JSON 对象自动映射到 C++ 结构体:

struct Person {
  std::string name;
  int age;
};
void from_json(const json& j, Person& p) {
  p.name = j.at("name").get<:string>();
  p.age = j.at("age").get();
}
Person p = j.get(); // 一行完成转换