最省心的方式是用nlohmann/json的get()配合nlohmann_define_type_intrusive宏实现自动递归解析;访问嵌套字段应优先用at()而非operator[]以防崩溃,可选字段用value()设默认值,数组批量转换需注意null和结构一致性,自定义from_json中需手动异常处理。

用 nlohmann/json 直接映射嵌套 JSON 到结构体
现代 C++ 最省心的方式是用 nlohmann/json 库的 get<t>()</t>,它支持自动递归解析嵌套对象。前提是你的结构体定义了 from_json 和 to_json 两个友元函数,或者用宏 NLOHMANN_DEFINE_TYPE_INTRUSIVE 或 NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE 声明映射规则。
比如有 JSON:
{
"user": {
"id": 1001,
"profile": {
"name": "Alice",
"tags": ["dev", "cpp"]
}
}
}
对应结构体可以这样写:
struct Profile {
std::string name;
std::vector<:string> tags;
};
struct User {
int id;
Profile profile;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Profile, name, tags)
NLOHMANN_DEFINE_TYPE_INTRUSIVE(User, id, profile)</:string>
然后一行就能解析:
json j = json::parse(json_str); User u = j["user"].get<user>();</user>
手动遍历嵌套对象时 key 不存在会崩溃
operator[] 在 key 不存在时会自动创建空值(比如 json::value_t::null),再调用 get<int>()</int> 就抛 json::type_error;而 at() 是安全访问——key 不存在直接 throw json::out_of_range,更适合容错处理。
DMap GL地图JSAPI(dmapgl)开发指南。用于编写、审查、调试 DMap 地图 API 代码,涵盖地图初始化、覆盖物渲染、图层管理、事件处理、控件交互等任务。当用户提及 dmap、dmapgl、jsapi‑gl 或相关地图开发需求时自动触发。
- 用
j.at("user").at("profile").at("name").get<:string>()</:string>显式捕获缺失字段 - 不要写
j["user"]["profile"]["name"].get<:string>()</:string>,万一中间某层 key 缺失,后续 get 会 crash - 如果字段可选,先用
contains()判断,或用value()提供默认值:j["user"].value("age", 0)
数组里嵌套对象的批量转换要小心类型擦除
JSON 数组如 "items": [{"id":1,"data":{"x":10}},{"id":2,"data":{"x":20}}],转成 std::vector<item></item> 时,get<vector>>()</vector> 要求每个元素都严格匹配 Item 的字段定义。常见翻车点:
- JSON 里某个
data是null,但结构体成员是Data data;(非指针/非 optional)→ 解析失败 - 想让
data可选,得声明为std::optional<data></data>并配套定义from_json - 若数组元素结构不统一(比如有的含
data,有的不含),别硬塞进一个结构体,改用json::array_t手动逐个检查is_object()和contains()
自定义 from_json 中嵌套解析失败不会自动回退
如果你手写 from_json,比如在 User 的解析里调用 j.at("profile").get<profile>()</profile>,一旦 Profile 解析出错(比如字段类型错、缺失必填项),整个 User 解析就终止,不会跳过或设默认值。
这时候得自己加异常防护:
void from_json(const json& j, User& u) {
u.id = j.at("id").get<int>();
try {
u.profile = j.at("profile").get<profile>();
} catch (const json::exception&) {
u.profile = {}; // 或记录警告
}
}</profile></int>
注意:nlohmann 的异常类型都是 json::exception 派生类,不能只 catch std::exception。
嵌套深、字段多时,from_json 里一层层 try-catch 很累,不如用 value() + 显式类型转换组合,或提前 validate 字段存在性和类型。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










