Serialize map as object and not array of pair for non std::string keys #3886
-
Hello I would like to serialize a map as object and not array of pair for non #include <iostream>
#include <nlohmann/json.hpp>
struct ThirdPartyKey {
bool operator==(const ThirdPartyKey &other) const { return true; }
};
void to_json(nlohmann::json &result, const ThirdPartyKey &nlohmann_json_t) {
result = "ThirdPartyKey";
}
struct MyCustomKey {
explicit operator std::string() const { return "MyCustomKey"; }
bool operator==(const MyCustomKey &other) const { return true; }
};
namespace std {
template <> struct hash<ThirdPartyKey> {
std::size_t operator()(const ThirdPartyKey &k) const { return 1; }
};
template <> struct hash<MyCustomKey> {
std::size_t operator()(const MyCustomKey &k) const { return 1; }
};
} // namespace std
int main() {
std::cout << nlohmann::json(std::unordered_map<std::string, int>{{"q", 0}}) << std::endl;
std::cout << nlohmann::json(std::unordered_map<ThirdPartyKey, int>{{{}, 1}}) << std::endl;
std::cout << nlohmann::json(std::unordered_map<MyCustomKey, int>{{{}, 1}}) << std::endl;
return 0;
} Output:
What I would like is:
I know I can implement a custom Reading the type_traits.hpp, I see that the requirement for the map to be used as a json object is that the key can construct a std::string. template<typename BasicJsonType, typename CompatibleObjectType>
struct is_compatible_object_type_impl <
BasicJsonType, CompatibleObjectType,
enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&&
is_detected<key_type_t, CompatibleObjectType>::value >>
{
using object_t = typename BasicJsonType::object_t;
// macOS's is_constructible does not play well with nonesuch...
static constexpr bool value =
is_constructible<typename object_t::key_type,
typename CompatibleObjectType::key_type>::value &&
is_constructible<typename object_t::mapped_type,
typename CompatibleObjectType::mapped_type>::value;
}; Does nlohmann provide a way to add a custom Sorry if this question was already asked I could not find any other threads about this. Best regards, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can follow the documentation (https://json.nlohmann.me/features/arbitrary_types/#how-do-i-convert-third-party-types) and try this: NLOHMANN_JSON_NAMESPACE_BEGIN
template <typename T>
struct adl_serializer<std::unordered_map<ThirdPartyKey, T>> {
static void to_json(json& j, const std::unordered_map<ThirdPartyKey, T>& m) {
for (auto it = m.begin(); it != m.end(); ++it)
{
j["ThirdPartyKey"] = it->second;
}
}
};
NLOHMANN_JSON_NAMESPACE_END This gives
Not function void to_json(nlohmann::json &result, const ThirdPartyKey &nlohmann_json_t) is not needed if you have an |
Beta Was this translation helpful? Give feedback.
You can follow the documentation (https://json.nlohmann.me/features/arbitrary_types/#how-do-i-convert-third-party-types) and try this:
This gives
Not function
is not needed if yo…