Skip to content

Commit

Permalink
feat: ser/deser u8string as json string, not array
Browse files Browse the repository at this point in the history
  • Loading branch information
Guekka committed Aug 19, 2023
1 parent 71fcdad commit 49efc6d
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions include/btu/common/json.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <btu/common/string.hpp>
#include <nlohmann/json.hpp>

#include <optional>
Expand Down Expand Up @@ -37,6 +38,18 @@ struct variant_switch<0>
};
} // namespace detail

namespace std {
inline void to_json(nlohmann::json &j, const u8string &str)
{
j = ::btu::common::as_ascii(str);
}

inline void from_json(const nlohmann::json &j, u8string &str)
{
str = ::btu::common::as_utf8(j.get<std::string>());
}
} // namespace std

namespace nlohmann {

template<typename T>
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ set(SOURCE_FILES
"${SOURCE_DIR}/utils.hpp"
"${SOURCE_DIR}/common/filesystem.cpp"
"${SOURCE_DIR}/common/functional.cpp"
"${SOURCE_DIR}/common/json.cpp"
"${SOURCE_DIR}/common/metaprogramming.cpp"
"${SOURCE_DIR}/common/string.cpp"
"${SOURCE_DIR}/bsa/archive.cpp"
Expand Down
21 changes: 21 additions & 0 deletions tests/common/json.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <btu/common/json.hpp>
#include <btu/common/string.hpp>
#include <catch.hpp>

TEST_CASE("std::u8string is converted to json as a string", "[src]")
{
SECTION("To json")
{
const auto str = u8"👍 👍 👍";
const auto json = nlohmann::json(str);
REQUIRE(json.is_string());
REQUIRE(json.get<std::string>() == btu::common::as_ascii(str));
}

SECTION("From json")
{
const auto json = R"("👍 👍 👍")"_json;
REQUIRE(json.is_string());
REQUIRE(json.get<std::u8string>() == u8"👍 👍 👍");
}
}

0 comments on commit 49efc6d

Please sign in to comment.