Search code examples
c++jsonserializationcpprest-sdk

cpprestsdk: unable to parse json input


For some reason, the for loop in fromJson method fails to iterate over available JSON fields. The way I understand it (based on the debugging), it is unable to read input string as JSON object. But when I check it in the debugger, I see the correct JSON string. The exact same code works for a different POD class.

The object:

struct Config
{
    Config();
    Config(Config&&) = default;
    Config& operator=(Config&&) = default;

    bool operator==(const Config& c) const;
    bool operator!=(const Config& c) const;

    bool isValid() const;

    unsigned short m_taskTimer;
    bool m_test;
};

Serialization/deserialization. fromJson fails to parse input string:

bool Serialization::fromJson(Controller::Config& c, const std::string& str)
try
{
    json::value temp;
    unsigned short count = 0;
    temp.parse(str);

    for (auto it = temp.as_object().cbegin(); it != temp.as_object().cend(); ++it)
    {
        const std::string& key = it->first;
        const json::value& value = it->second;

        if (key == "taskTimer")
        {
            c.m_taskTimer = value.as_integer();
            ++count;
            continue;
        }

        if (key == "test")
        {
            c.m_test = value.as_bool();
            ++count;
            continue;
        }

        return false;
    }

    if (count != 2)
    {
        return false;
    }

    return true;
}
catch (...)
{
    return false;
}

std::string Serialization::toJson(const Controller::Config& c)
{
    json::value temp;
    temp["taskTimer"] = json::value::number(c.m_taskTimer);
    temp["test"] = json::value::boolean(c.m_test);

    return temp.serialize();
}

Test:

Controller::Config cc1, cc2;
cc1.m_taskTimer = 300;
cc1.m_test = true;
Serialization::fromJson(cc2, Serialization::toJson(cc1));
assert(cc1 == cc2);

What I am trying to understand is why does it fail to iterate over fields? The temp.parse(str) line works, so the library thinks the input is valid.


Solution

  • Changing temp.parse(str) to auto temp = json::value::parse(str) fixed the problem.