将spdlog::level::level_enum转换为nlohmann::json或从nlohmann::json转换为spdlog::level::level_enum

b5lpy0ml  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(46)

在nlohmann-json文档中的this tutorial的帮助下,我尝试将JSON字符串中的键值对转换为spdlog::level::level_enum
使用以下JSON

{
  "log-level": "info",
  "log-path": "/var/log/info/"
}

字符串
和C++代码

#include "spdlog/spdlog.h"
#include "nlohmann/json.hpp"

NLOHMANN_JSON_SERIALIZE_ENUM(spdlog::level::level_enum, {
    {spdlog::level::level_enum::trace, "trace"},
    {spdlog::level::level_enum::debug, "debug"},
    {spdlog::level::level_enum::info, "info"},
    {spdlog::level::level_enum::warn, "warn"},
    {spdlog::level::level_enum::err, "err"},
    {spdlog::level::level_enum::critical, "critical"},
    {spdlog::level::level_enum::off, "off"}
})

int main()
{
    std::string input = R"({
  "log-level": "info",
  "log-path": "/var/log/info/"
}
)";
    auto json = nlohmann::json::parse(input);
    json["log-level"]. template get<spdlog::level::level_enum>();
}


,我尝试将"log-level"的值(即"info")转换为spdlog::level::level_enum
但我得到了这个错误:

terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_2::detail::type_error'
  what():  [json.exception.type_error.302] type must be number, but is object


有人能告诉我我做错了什么,我如何转换"log-level": "some-spdlog-level"spdlog::level::level_enum
谢谢

w80xi6nr

w80xi6nr1#

请参阅您链接到的文档中的声明:
NLOHMANN_JSON_SERIALIZE_ENUM()必须在枚举类型的命名空间(可以是全局命名空间)中声明,否则库将无法定位它,并且它将默认为整数序列化。
NLOHMANN_JSON_SERIALIZE_ENUM移动到spdlog命名空间中可以解决这个问题:

namespace spdlog::level {
    NLOHMANN_JSON_SERIALIZE_ENUM(spdlog::level::level_enum, {
        {spdlog::level::level_enum::trace, "trace"},
        {spdlog::level::level_enum::debug, "debug"},
        {spdlog::level::level_enum::info, "info"},
        {spdlog::level::level_enum::warn, "warn"},
        {spdlog::level::level_enum::err, "err"},
        {spdlog::level::level_enum::critical, "critical"},
        {spdlog::level::level_enum::off, "off"}
    })
}

字符串
https://godbolt.org/z/ozWq3xT83

相关问题