Skip to content

get enum with default value #5036

@IamRezaMousavi

Description

@IamRezaMousavi

Description

I want to get enum value or use default one if it has error, but I can't

sample code:

#include <nlohmann/json.hpp>

#include <iostream>
#include <string>

enum class UserRequestType {
    GetUser,
    AddUser,
    Unknown
};

// clang-format off
NLOHMANN_JSON_SERIALIZE_ENUM(UserRequestType, {
  {UserRequestType::GetUser, "get"},
  {UserRequestType::AddUser, "add"},
  {UserRequestType::Unknown, "unknown"}
})
// clang-format on

int main(int argc, char const *argv[]) {
  std::string jtext = "{\"type\": \"invalidtype\"}";

  nlohmann::json j = nlohmann::json::parse(jtext);
  UserRequestType t = j.value("type", UserRequestType::Unknown);

  std::cout << static_cast<int>(t) << '\n'; // got 0 (UserRequestType::GetUser)
  return 0;
}

I know I can use j["type"].get<UserRequestType>() and reorder the enum to use first one as default, but json.value(string, UserRequestType has a bug

Reproduction steps

compile and run the code

Expected vs. actual results

expected j["type"].get<UserRequestType>() throw exception and j.value("type", UserRequestType::Unknown) return default one

Minimal code example

Error messages

Compiler and operating system

Ubuntu 24.04, GCC 13.3.0

Library version

3.11.3-1

Validation

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: bugsolution: proposed fixa fix for the issue has been proposed and waits for confirmation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions