/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ (test suite) | | |__ | | | | | | version 2.0.7 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License . Copyright (c) 2013-2016 Niels Lohmann . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include #include #include #include "catch.hpp" #include "json.hpp" using nlohmann::json; namespace udt { enum class country { china, france, russia }; struct age { int m_val; }; struct name { std::string m_val; }; struct address { std::string m_val; }; struct person { age m_age; name m_name; country m_country; }; struct contact { person m_person; address m_address; }; struct contact_book { name m_book_name; std::vector m_contacts; }; } // to_json methods namespace udt { // templates because of the custom_json tests (see below) template void to_json(Json& j, age a) { j = a.m_val; } template void to_json(Json& j, name const& n) { j = n.m_val; } template void to_json(Json& j, country c) { switch (c) { case country::china: j = u8"中华人民共和国"; return; case country::france: j = "France"; return; case country::russia: j = u8"Российская Федерация"; return; } } template void to_json(Json& j, person const& p) { j = Json{{"age", p.m_age}, {"name", p.m_name}, {"country", p.m_country}}; } void to_json(nlohmann::json& j, address const& a) { j = a.m_val; } void to_json(nlohmann::json& j, contact const& c) { j = json{{"person", c.m_person}, {"address", c.m_address}}; } void to_json(nlohmann::json& j, contact_book const& cb) { j = json{{"name", cb.m_book_name}, {"contacts", cb.m_contacts}}; } // operators bool operator==(age lhs, age rhs) { return lhs.m_val == rhs.m_val; } bool operator==(address const& lhs, address const& rhs) { return lhs.m_val == rhs.m_val; } bool operator==(name const& lhs, name const& rhs) { return lhs.m_val == rhs.m_val; } bool operator==(person const& lhs, person const& rhs) { return std::tie(lhs.m_name, lhs.m_age) == std::tie(rhs.m_name, rhs.m_age); } bool operator==(contact const& lhs, contact const& rhs) { return std::tie(lhs.m_person, lhs.m_address) == std::tie(rhs.m_person, rhs.m_address); } bool operator==(contact_book const& lhs, contact_book const& rhs) { return std::tie(lhs.m_book_name, lhs.m_contacts) == std::tie(rhs.m_book_name, rhs.m_contacts); } } // from_json methods namespace udt { template void from_json(Json const& j, age& a) { a.m_val = j.template get(); } template void from_json(Json const& j, name& n) { n.m_val = j.template get(); } template void from_json(Json const& j, country& c) { const auto str = j.template get(); static const std::map m = { {u8"中华人民共和国", country::china}, {"France", country::france}, {"Российская Федерация", country::russia} }; const auto it = m.find(str); // TODO test exceptions c = it->second; } template void from_json(Json const& j, person& p) { p.m_age = j["age"].template get(); p.m_name = j["name"].template get(); p.m_country = j["country"].template get(); } void from_json(nlohmann::json const& j, address& a) { a.m_val = j.get(); } void from_json(nlohmann::json const& j, contact& c) { c.m_person = j["person"].get(); c.m_address = j["address"].get
(); } void from_json(nlohmann::json const& j, contact_book& cb) { cb.m_book_name = j["name"].get(); cb.m_contacts = j["contacts"].get>(); } } TEST_CASE("basic usage", "[udt]") { // a bit narcissic maybe :) ? const udt::age a { 23 }; const udt::name n{"theo"}; const udt::country c{udt::country::france}; const udt::person sfinae_addict{a, n, c}; const udt::person senior_programmer{{42}, {u8"王芳"}, udt::country::china}; const udt::address addr{"Paris"}; const udt::contact cpp_programmer{sfinae_addict, addr}; const udt::contact_book book{{"C++"}, {cpp_programmer, {senior_programmer, addr}}}; SECTION("conversion to json via free-functions") { CHECK(json(a) == json(23)); CHECK(json(n) == json("theo")); CHECK(json(c) == json("France")); CHECK(json(sfinae_addict) == R"({"name":"theo", "age":23, "country":"France"})"_json); CHECK(json("Paris") == json(addr)); CHECK(json(cpp_programmer) == R"({"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"})"_json); CHECK( json(book) == u8R"({"name":"C++", "contacts" : [{"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"}, {"person" : {"age":42, "country":"中华人民共和国", "name":"王芳"}, "address":"Paris"}]})"_json); } SECTION("conversion from json via free-functions") { const auto big_json = u8R"({"name":"C++", "contacts" : [{"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"}, {"person" : {"age":42, "country":"中华人民共和国", "name":"王芳"}, "address":"Paris"}]})"_json; const auto parsed_book = big_json.get(); const auto book_name = big_json["name"].get(); const auto contacts = big_json["contacts"].get>(); const auto contact_json = big_json["contacts"].at(0); const auto contact = contact_json.get(); const auto person = contact_json["person"].get(); const auto address = contact_json["address"].get(); const auto age = contact_json["person"]["age"].get(); const auto country = contact_json["person"]["country"].get(); const auto name = contact_json["person"]["name"].get(); CHECK(age == a); CHECK(name == n); CHECK(country == c); CHECK(address == addr); CHECK(person == sfinae_addict); CHECK(contact == cpp_programmer); CHECK(contacts == book.m_contacts); CHECK(book_name == udt::name{"C++"}); CHECK(book == parsed_book); } } namespace udt { struct legacy_type { std::string number; }; } namespace nlohmann { template struct adl_serializer> { static void to_json(json& j, std::shared_ptr const& opt) { if (opt) { j = *opt; } else { j = nullptr; } } static void from_json(json const& j, std::shared_ptr& opt) { if (j.is_null()) { opt = nullptr; } else { opt.reset(new T(j.get())); } } }; template <> struct adl_serializer { static void to_json(json& j, udt::legacy_type const& l) { j = std::stoi(l.number); } static void from_json(json const& j, udt::legacy_type& l) { l.number = std::to_string(j.get()); } }; } TEST_CASE("adl_serializer specialization", "[udt]") { SECTION("partial specialization") { SECTION("to_json") { std::shared_ptr optPerson; json j = optPerson; CHECK(j.is_null()); optPerson.reset(new udt::person{{42}, {"John Doe"}}); j = optPerson; CHECK_FALSE(j.is_null()); CHECK(j.get() == *optPerson); } SECTION("from_json") { auto person = udt::person{{42}, {"John Doe"}}; json j = person; auto optPerson = j.get>(); REQUIRE(optPerson); CHECK(*optPerson == person); j = nullptr; optPerson = j.get>(); CHECK(!optPerson); } } SECTION("total specialization") { SECTION("to_json") { udt::legacy_type lt{"4242"}; json j = lt; CHECK(j.get() == 4242); } SECTION("from_json") { json j = 4242; auto lt = j.get(); CHECK(lt.number == "4242"); } } } namespace nlohmann { template <> struct adl_serializer> { static void to_json(json& j, std::vector const&) { j = "hijacked!"; } static void from_json(json const&, std::vector& opt) { opt = {42.0, 42.0, 42.0}; } }; } TEST_CASE("even supported types can be specialized", "[udt]") { json j = std::vector {1.0, 2.0, 3.0}; CHECK(j.dump() == R"("hijacked!")"); auto f = j.get>(); CHECK((f == std::vector{42.0, 42.0, 42.0})); } namespace nlohmann { template struct adl_serializer> { static void to_json(json& j, std::unique_ptr const& opt) { if (opt) { j = *opt; } else { j = nullptr; } } // this is the overload needed for non-copyable types, static std::unique_ptr from_json(json const& j) { if (j.is_null()) { return nullptr; } else { return std::unique_ptr(new T(j.get())); } } }; } TEST_CASE("Non-copyable types", "[udt]") { SECTION("to_json") { std::unique_ptr optPerson; json j = optPerson; CHECK(j.is_null()); optPerson.reset(new udt::person{{42}, {"John Doe"}, udt::country::russia}); j = optPerson; CHECK_FALSE(j.is_null()); CHECK(j.get() == *optPerson); } SECTION("from_json") { auto person = udt::person{{42}, {"John Doe"}, udt::country::russia}; json j = person; auto optPerson = j.get>(); REQUIRE(optPerson); CHECK(*optPerson == person); j = nullptr; optPerson = j.get>(); CHECK(!optPerson); } } // custom serializer - advanced usage // pack structs that are pod-types (but not scalar types) // relies on adl for any other type template struct pod_serializer { // use adl for non-pods, or scalar types template < typename Json, typename U = T, typename std::enable_if< not(std::is_pod::value and std::is_class::value), int>::type = 0> static void from_json(Json const &j, U &t) { using nlohmann::from_json; from_json(j, t); } // special behaviour for pods template ::value and std::is_class::value, int>::type = 0> static void from_json(Json const &j, U &t) { std::uint64_t value; // TODO The following block is no longer relevant in this serializer, make another one that shows the issue // the problem arises only when one from_json method is defined without any constraint // // Why cannot we simply use: j.get() ? // Well, with the current experiment, the get method looks for a from_json // function, which we are currently defining! // This would end up in a stack overflow. Calling nlohmann::from_json is a // workaround (is it?). // I shall find a good way to avoid this once all constructors are converted // to free methods // // In short, constructing a json by constructor calls to_json // calling get calls from_json, for now, we cannot do this in custom // serializers nlohmann::from_json(j, value); auto bytes = static_cast(static_cast(&value)); std::memcpy(&t, bytes, sizeof(value)); } template < typename Json, typename U = T, typename std::enable_if< not(std::is_pod::value and std::is_class::value), int>::type = 0> static void to_json(Json &j, T const &t) { using nlohmann::to_json; to_json(j, t); } template ::value and std::is_class::value, int>::type = 0> static void to_json(Json &j, T const &t) noexcept { auto bytes = static_cast(static_cast(&t)); std::uint64_t value = bytes[0]; for (auto i = 1; i < 8; ++i) value |= std::uint64_t{bytes[i]} << 8 * i; nlohmann::to_json(j, value); } }; namespace udt { struct small_pod { int begin; char middle; short end; }; struct non_pod { std::string s; }; template void to_json(Json& j, non_pod const& np) { j = np.s; } template void from_json(Json const& j, non_pod& np) { np.s = j.template get(); } bool operator==(small_pod lhs, small_pod rhs) noexcept { return std::tie(lhs.begin, lhs.middle, lhs.end) == std::tie(rhs.begin, rhs.middle, rhs.end); } bool operator==(non_pod const &lhs, non_pod const &rhs) noexcept { return lhs.s == rhs.s; } std::ostream& operator<<(std::ostream& os, small_pod l) { return os << "begin: " << l.begin << ", middle: " << l.middle << ", end: " << l.end; } } TEST_CASE("custom serializer for pods", "[udt]") { using custom_json = nlohmann::basic_json; auto p = udt::small_pod{42, '/', 42}; custom_json j = p; auto p2 = j.get(); CHECK(p == p2); auto np = udt::non_pod{{"non-pod"}}; custom_json j2 = np; auto np2 = j2.get(); CHECK(np == np2); } template struct another_adl_serializer; using custom_json = nlohmann::basic_json; template struct another_adl_serializer { static void from_json(custom_json const& j , T& t) { using nlohmann::from_json; from_json(j, t); } static void to_json(custom_json& j , T const& t) { using nlohmann::to_json; to_json(j, t); } }; TEST_CASE("custom serializer that does adl by default", "[udt]") { using json = nlohmann::json; auto me = udt::person{23, "theo", udt::country::france}; json j = me; custom_json cj = me; CHECK(j.dump() == cj.dump()); CHECK(me == j.get()); CHECK(me == cj.get()); }