Allow boost url and url_view to be added to json
The latest version of nlohmann seems to have support for adding any
arbitrary iterable object as an array in json. Unfortunately, because
boost::urls::url produces at iterable of unsigned char, this means that
trying to encode urls leads to something like:
"@odata.id": [
47,
114,
101,
100,
102
]
Which is super unhelpful in that it does this implicitly. Given this
behavior, there are two options here, make it so that code doesn't
compile, or rely on the adl_serializer to just do the expected thing.
This patchset opts for the later, to simply to the reasonable behavior,
and call string() on the url before loading it into the json.
Tested: Unit tests passing. Fixes bug in subsequent patchset.
Signed-off-by: Ed Tanous <edtanous@google.com>
Change-Id: Id2f49bc8bd7153a0ad0c0fa8be2e13ce7c538e7f
diff --git a/http/ut/utility_test.cpp b/http/ut/utility_test.cpp
index bab21f9..1600e7f 100644
--- a/http/ut/utility_test.cpp
+++ b/http/ut/utility_test.cpp
@@ -247,5 +247,14 @@
crow::black_magic::getParameterTag("<uint><double><int>"));
}
+TEST(URL, JsonEncoding)
+{
+ using nlohmann::json;
+
+ std::string urlString = "/foo";
+ EXPECT_EQ(json(boost::urls::url(urlString)), urlString);
+ EXPECT_EQ(json(boost::urls::url_view(urlString)), urlString);
+}
+
} // namespace
} // namespace crow::utility
diff --git a/http/utility.hpp b/http/utility.hpp
index da457be..0b1743f 100644
--- a/http/utility.hpp
+++ b/http/utility.hpp
@@ -6,6 +6,7 @@
#include <boost/callable_traits.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/url/url.hpp>
+#include <nlohmann/json.hpp>
#include <array>
#include <chrono>
@@ -781,3 +782,27 @@
} // namespace utility
} // namespace crow
+
+namespace nlohmann
+{
+template <>
+struct adl_serializer<boost::urls::url>
+{
+ // nlohmann requires a specific casing to look these up in adl
+ // NOLINTNEXTLINE(readability-identifier-naming)
+ static void to_json(json& j, const boost::urls::url& url)
+ {
+ j = url.string();
+ }
+};
+
+template <>
+struct adl_serializer<boost::urls::url_view>
+{
+ // NOLINTNEXTLINE(readability-identifier-naming)
+ static void to_json(json& j, const boost::urls::url_view& url)
+ {
+ j = url.string();
+ }
+};
+} // namespace nlohmann