nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.92k stars 6.71k forks source link

compile error in from_json converting to container with std::pair #1299

Closed brainiac closed 6 years ago

brainiac commented 6 years ago

It looks like the change to fix #1292 (11fecc25af64529599e9a24675651115d6bae322) causes a regression when converting to a container std::pair with a non-trivial type. I didn't see a unit test that covers this case.

Example code that show the failure: https://wandbox.org/permlink/BVgyd1o4MW60bqvS

#include "nlohmann/json.hpp"

#include <iostream>
#include <map>
#include <string>

using json = nlohmann::json;

struct Data
{
    std::string a;
    std::string b;
};

void from_json(const json& j, Data& data)
{
    j["a"].get_to(data.a);
    j["b"].get_to(data.b);
}

int main()
{
    // create a JSON object
    json j =
    {
        {"1", {
            {"a", "testa_1"},
            {"b", "testa_1"}
        }},
        {"2", {
            {"a", "testa_2"},
            {"b", "testb_2"}
        }},
        {"3", {
            {"a", "testa_3"},
            {"b", "testb_3"}
        }},
    };

    std::map<std::string, Data> data;
    j.get_to(data);

    for (const auto& p : data)
    {
        std::cout << p.first << " -> " << p.second.a << ", " << p.second.b << std::endl;
    }
}
theodelrieu commented 6 years ago

Thanks for the report.

Seems like the std::map overload is not chosen, thus it falls back trying to construct a std::pair<**const** std::string, std::string>...

I'll fix it tomorrow.

nlohmann commented 6 years ago

@brainiac Could you please check the fix in #1301?

brainiac commented 6 years ago

Hi @nlohmann and @theodelrieu, thanks for looking into this. It looks like with the fix in #1301 it is working now.