summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEd Tanous <edtanous@google.com>2022-05-25 22:28:09 +0300
committerEd Tanous <ed@tanous.net>2022-06-02 02:33:46 +0300
commit71f2db758154e3a0e1b5dbd4698f5dddd31c10c0 (patch)
treeeddd24af8b230aa626fc09731aceabc48d3be34b
parent72c3ae33bd127f8cd5887000a45adf13a56c7582 (diff)
downloadbmcweb-71f2db758154e3a0e1b5dbd4698f5dddd31c10c0.tar.xz
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
-rw-r--r--http/ut/utility_test.cpp9
-rw-r--r--http/utility.hpp25
2 files changed, 34 insertions, 0 deletions
diff --git a/http/ut/utility_test.cpp b/http/ut/utility_test.cpp
index bab21f96c0..1600e7f54f 100644
--- a/http/ut/utility_test.cpp
+++ b/http/ut/utility_test.cpp
@@ -247,5 +247,14 @@ TEST(Router, ParameterTagging)
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 da457bec7b..0b1743f228 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 @@ inline bool validateAndSplitUrl(std::string_view destUrl, std::string& urlProto,
} // 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