Skip to content

Commit

Permalink
add a serialiser for xvariant to json
Browse files Browse the repository at this point in the history
  • Loading branch information
madhur-tandon committed Aug 3, 2020
1 parent 24d3c31 commit 5290221
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
13 changes: 12 additions & 1 deletion include/xtl/xjson.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

#include <cstddef>
#include <string>

#include "xtl/xvariant.hpp"
#include "nlohmann/json.hpp"

namespace xtl
Expand Down Expand Up @@ -82,4 +82,15 @@ namespace xtl
}
}

// overloading in the mpark namespace because `xtl::variant` is just a typedef on `mpark::variant`
namespace mpark
{
template <class... Ts>
void to_json(nlohmann::json& j, const xtl::variant<Ts...>& data) {
xtl::visit(
[&] (const auto & arg) { j = arg; }, data
);
}
}

#endif
22 changes: 22 additions & 0 deletions test/test_xvariant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
#include "gtest/gtest.h"
#include "xtl/xtl_config.hpp"

#ifdef HAVE_NLOHMANN_JSON
#include "xtl/xjson.hpp"
#endif

using namespace std::literals;

namespace xtl
Expand Down Expand Up @@ -203,4 +207,22 @@ namespace xtl

EXPECT_TRUE(res);
}

#ifdef HAVE_NLOHMANN_JSON
TEST(xvariant, json)
{
typedef xtl::xvariant<double, std::string> stringNumType;

nlohmann::json j1;
stringNumType m1 = "Hello";
j1["salutation"] = m1;
EXPECT_EQ(j1.at("salutation"), "Hello");

nlohmann::json j2;
stringNumType m2 = 3.0;
j2["num"] = m2;
EXPECT_EQ(j2.at("num"), 3.0);
}
#endif

}

0 comments on commit 5290221

Please sign in to comment.