Skip to content

Serialize map as object and not array of pair for non std::string keys #3886

Answered by nlohmann
alexdesaint asked this question in Q&A
Discussion options

You must be logged in to vote

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

{"q":0}
{"ThirdPartyKey":1}
{"MyCustomKey":1}

Not function

void to_json(nlohmann::json &result, const ThirdPartyKey &nlohmann_json_t)

is not needed if yo…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@alexdesaint
Comment options

Answer selected by alexdesaint
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants