首页 > 解决方案 > nlohmann json没有成员“异常”错误(vscode c++)

问题描述

我正在尝试构建一个简单的 catch 结构,但出现以下与 nlohmann json 库相关的错误。

error: ‘exception’ in ‘using json = class nlohmann::basic_json<> {aka class nlohmann::basic_json<>}’ does not name a type
     catch (nlohmann::json::exception& e)

这是代码;

#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;
            }

关于“异常”有如下解释:

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"

但我很确定 nlohmann/json.hpp 中存在“异常”,因为我检查过。

部分也没有问题nlohmann::json json;

我究竟做错了什么?

谢谢

标签: c++visual-studio-codenlohmann-json

解决方案


我有同样的问题。默认情况下#include <nlohmann/json.hpp>在所有系统路径中搜索指定文件。在我的情况下(Ubuntu 18.04),它是 /usr/include/nlohmann/json.hpp,它的版本为 2.1.1,并产生了关于 'nlohmann::json::exception& e' 的相同错误。但是我的本地目录中有 single_include 版本: ~/projects/json/single_include/nlohmann/json.hpp 有版本 3.9.1 没有那个错误。

因此,只需更改您的包含语句以使用正确的版本:

#include "your_src_dir/single_include/nlohmann/json.hpp"

g++ -I或者,使用标志指定包含路径。


推荐阅读