Skip to content

Commit

Permalink
feat: crazy serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
MistEO committed Oct 20, 2023
1 parent ec0f744 commit c0965f7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
9 changes: 5 additions & 4 deletions include/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2577,21 +2577,22 @@ namespace _serialization_helper
using char_t = typename string_t::value_type;
using ostringstream_t = std::basic_ostringstream<char_t, std::char_traits<char_t>, std::allocator<char_t>>;

static constexpr bool stream = loose;

template <typename input_t>
string_t operator()(input_t&& arg) const
{
if constexpr (std::is_constructible_v<string_t, input_t>) {
return string_t(std::forward<input_t>(arg));
}
else if constexpr (stream && has_output_operator<char_t, input_t>::value) {
else if constexpr (!loose) {
static_assert(!sizeof(input_t), "Unable to convert type to string.");
}
else if constexpr (has_output_operator<char_t, input_t>::value) {
ostringstream_t os;
os << std::forward<input_t>(arg);
return std::move(os).str();
}
else {
static_assert(!sizeof(input_t), "Unable to convert type to string.");
return serialize<loose, input_t, string_t>(std::forward<input_t>(arg), *this).dumps();
}
}
};
Expand Down
6 changes: 3 additions & 3 deletions sample/sample.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,9 +241,9 @@ bool serializing()
std::vector<std::list<std::set<int>>> complex { { { 1, 2, 3 }, { 4, 5 } }, { { 6 }, { 7, 8 } } };
root["complex"] = json::serialize<false>(complex);

std::map<std::string, std::map<int, std::vector<double>>> more_complex {
{ "key1", { { 1, { 0.1, 0.2 } }, { 2, { 0.2, 0.3 } } } },
{ "key2", { { 3, { 0.4 } }, { 4, { 0.5, 0.6, 0.7 } } } },
std::map<std::vector<std::string>, std::map<int, std::vector<double>>> more_complex {
{ { "i", "am", "key1" }, { { 1, { 0.1, 0.2 } }, { 2, { 0.2, 0.3 } } } },
{ { "key2" }, { { 3, { 0.4 } }, { 4, { 0.5, 0.6, 0.7 } } } },
};
// the "std::map<int, xxx>" cannot be converted to json because the key is "int",
// you can set the template parameter "loose" of "serialize" to true, which will make a more relaxed conversion.
Expand Down

0 comments on commit c0965f7

Please sign in to comment.