VSCode C++环境下nlohmann json报无exception成员错误如何解决
nlohmann json库使用
nlohmann::json::exception捕获异常报错问题排查 报错信息
error: ‘exception’ in ‘using json = class nlohmann::basic_json<> {aka class nlohmann::basic_json<>}’ does not name a type catch (nlohmann::json::exception& e)
IDE诊断提示
class "nlohmann::basic_json<std::map, std::vector, std::__cxx11::string, bool, int64_t, uint64_t, double, std::allocator, nlohmann::adl_serializer>" has no member "exception"
相关代码片段
#include <iostream> #include <nlohmann/json.hpp> namespace company { namespace project { class Serializable { public: virtual void read(const nlohmann::json& json) = 0; virtual void write(nlohmann::json& json) const = 0; bool load(const std::string& fileName) { try { nlohmann::json json; std::ifstream f(fileName.c_str()); if (f.good()) { f >> json; read(json); return true; } } catch (nlohmann::json::exception& e) { projectError << "Cant read json " << fileName << " Exception: " << e.what(); } projectError << "Cant read json " << fileName; return false; }
已确认的前置条件
- nlohmann/json.hpp头文件中确实存在exception成员类型定义
- 代码中
nlohmann::json json;语句无编译报错
问题原因与对应解决方案
原因1:标识符重名冲突
你在try块内定义的局部变量名json和类型名nlohmann::json产生了作用域内的名称遮蔽,部分编译器会优先将json识别为局部变量而非类型,导致解析nlohmann::json::exception失败。
解决方案:修改局部变量名,避免和类型名重名,例如改为
nlohmann::json json_obj;即可。另外你的代码里还缺少<fstream>头文件引用,会导致std::ifstream相关编译错误,建议同步补上。
原因2:库版本不匹配
项目实际编译时引入的nlohmann json库版本低于v3.0.0,早期版本的异常类型并非内嵌在basic_json中的成员类型。
解决方案:升级nlohmann json库到v3.0.0及以上稳定版本即可。
原因3:宏污染
如果项目中引入了Windows.h等会定义exception宏的头文件,宏替换会破坏exception标识符的语义,导致编译器无法识别类型。
解决方案:调整头文件引入顺序,将
nlohmann/json.hpp放在冲突头文件之前引入;或者在引入冲突头文件前添加#define NOGDI、在catch块前临时添加#undef exception解决宏替换问题。
内容的提问来源于stack exchange,提问作者Tyr
相关产品推荐
相关产品推荐

