是否可以为枚举定义字符串值?比如将struct中的enum在json序列化中翻译为string
Yhaiyang opened this issue · 4 comments
Yhaiyang commented
是否可以为枚举定义字符串值?比如将struct中的enum在json序列化中翻译为string
bbbgan commented
目前只是简单把enum序列化成数字,
bbbgan commented
已经支持了将枚举处理成字符串的形式,默认还是数字的形式:下面是文档:
https://github.com/qicosmos/iguana#how-to-handle-the-enum-type-as-strings
下面是json的示例代码,yaml、xml类似:
Lines 215 to 279 in 37c363e
enum class Fruit { | |
APPLE = 9999, | |
BANANA = -4, | |
ORANGE = 10, | |
MANGO = 99, | |
CHERRY = 7, | |
GRAPE = 100000 | |
}; | |
enum class Color { | |
BULE = 10, | |
RED = 15, | |
}; | |
enum class Status { stop = 10, start }; | |
namespace iguana { | |
template <> struct enum_value<Fruit> { | |
constexpr static std::array<int, 6> value = {9999, -4, 10, 99, 7, 100000}; | |
}; | |
} // namespace iguana | |
struct test_enum_t { | |
Fruit a; | |
Fruit b; | |
Fruit c; | |
Fruit d; | |
Fruit e; | |
Fruit f; | |
Color g; | |
Color h; | |
}; | |
REFLECTION(test_enum_t, a, b, c, d, e, f, g, h); | |
TEST_CASE("test enum") { | |
auto validator = [](test_enum_t e) { | |
CHECK(e.a == Fruit::APPLE); | |
CHECK(e.b == Fruit::BANANA); | |
CHECK(e.c == Fruit::ORANGE); | |
CHECK(e.d == Fruit::MANGO); | |
CHECK(e.e == Fruit::CHERRY); | |
CHECK(e.f == Fruit::GRAPE); | |
CHECK(e.g == Color::BULE); | |
CHECK(e.h == Color::RED); | |
}; | |
std::string str = R"( | |
{ | |
"a": "APPLE", | |
"b": "BANANA", | |
"c": "ORANGE", | |
"d": "MANGO", | |
"e": "CHERRY", | |
"f": "GRAPE", | |
"g": 10, | |
"h": 15 | |
} | |
)"; | |
test_enum_t e; | |
iguana::from_json(e, str); | |
validator(e); | |
std::string ss; | |
iguana::to_json(e, ss); | |
std::cout << ss << std::endl; | |
test_enum_t e1; | |
iguana::from_json(e1, ss); | |
validator(e1); | |
} |