-
-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Description
Description
I had a json document with an invalid enum string. I would like an exception to be raised if the string is not a known conversion back to the enum. I don't want to have to add and check an Unknown
or Invalid
enum value which would only be used for json serialization.
This is well documented: "undefined JSON values will default to the first specified conversion." but is IMO is surprising behavior since we throw json.exception.type_error
's for other type conversions if they fail (like converting an integer in the json document to a std::string
)
This is maybe only a good idea for strongly typed enum class
's.
Reproduction steps
namespace ns
{
enum class Color
{
red, green, blue // I don't want to define an unknown item just used for json deserialization
};
NLOHMANN_JSON_SERIALIZE_ENUM(Color,
{
{ Color::red, "red" },
{ Color::green, "green" },
{ Color::blue, "blue" }
})
}
json some_color_json = "pink";
try {
auto color = some_color_json.get<ns::Color>();
} catch (json::type_error& e) {
printf("Invalid color!\n");
}
Expected vs. actual results
Expected: It prints 'invalid color'
Actual: color
gets set to Color::red
I believe the behavior I am after can be achieved by with this patch
diff --git a/include/nlohmann/detail/macro_scope.hpp b/include/nlohmann/detail/macro_scope.hpp
index 6248bea..9916aac 100644
--- a/include/nlohmann/detail/macro_scope.hpp
+++ b/include/nlohmann/detail/macro_scope.hpp
@@ -215,7 +215,9 @@
{ \
return ej_pair.first == e; \
}); \
- j = ((it != std::end(m)) ? it : std::begin(m))->second; \
+ if (it == std::end(m))
+ throw ...
+ j = it;
} \
template<typename BasicJsonType> \
inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
@@ -227,7 +229,9 @@
{ \
return ej_pair.second == j; \
}); \
- e = ((it != std::end(m)) ? it : std::begin(m))->first; \
+ if (it == std::end(m))
+ throw ...
+ e = it;
}
// Ugly macros to avoid uglier copy-paste when specializing basic_json. They
Minimal code example
No response
Error messages
No response
Compiler and operating system
clang 15.0.7
Library version
v3.11.2
Validation
- The bug also occurs if the latest version from the
develop
branch is used. - I can successfully compile and run the unit tests.