1
0
mirror of https://github.com/nlohmann/json.git synced 2025-07-29 23:01:16 +03:00

Add serialization-only user defined type macros (#3816)

This commit is contained in:
Vyacheslav Zhdanovskiy
2023-11-26 15:18:20 +03:00
committed by GitHub
parent 5d931c59a3
commit 360ce457f4
15 changed files with 293 additions and 13 deletions

View File

@ -279,6 +279,44 @@ class person_with_public_alphabet
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person_with_public_alphabet, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)
class person_without_default_constructor_1
{
public:
std::string name;
int age;
bool operator==(const person_without_default_constructor_1& other) const
{
return name == other.name && age == other.age;
}
person_without_default_constructor_1(std::string name_, int age_)
: name{std::move(name_)}
, age{age_}
{}
NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(person_without_default_constructor_1, name, age)
};
class person_without_default_constructor_2
{
public:
std::string name;
int age;
bool operator==(const person_without_default_constructor_2& other) const
{
return name == other.name && age == other.age;
}
person_without_default_constructor_2(std::string name_, int age_)
: name{std::move(name_)}
, age{age_}
{}
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(person_without_default_constructor_2, name, age)
} // namespace persons
TEST_CASE_TEMPLATE("Serialization/deserialization via NLOHMANN_DEFINE_TYPE_INTRUSIVE and NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE", T,
@ -412,3 +450,25 @@ TEST_CASE_TEMPLATE("Serialization/deserialization of classes with 26 public/priv
}
}
}
TEST_CASE_TEMPLATE("Serialization of non-default-constructible classes via NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE and NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE", T,
persons::person_without_default_constructor_1,
persons::person_without_default_constructor_2)
{
SECTION("person")
{
{
// serialization of a single object
T person{"Erik", 1};
CHECK(json(person).dump() == "{\"age\":1,\"name\":\"Erik\"}");
// serialization of a container with objects
std::vector<T> const two_persons
{
{"Erik", 1},
{"Kyle", 2}
};
CHECK(json(two_persons).dump() == "[{\"age\":1,\"name\":\"Erik\"},{\"age\":2,\"name\":\"Kyle\"}]");
}
}
}