1
0
mirror of https://github.com/binary-kitchen/doorlockd synced 2024-11-16 03:59:11 +01:00
doorlockd-mirror/doorlockd/lib/response.cpp

45 lines
991 B
C++
Raw Normal View History

2015-09-25 00:25:26 +02:00
#include <exception>
2015-09-22 21:22:48 +02:00
#include <json/json.h>
#include "response.h"
2015-09-25 00:25:26 +02:00
#include "util.h"
2015-09-22 21:22:48 +02:00
const std::string Response::_codeKey = "code";
const std::string Response::_messageKey = "message";
Response::operator bool() const
{
return code == Response::Code::Success;
}
std::string Response::toJson() const
{
Json::Value response;
Json::StyledWriter writer;
response[_codeKey] = code;
response[_messageKey] = message;
return writer.write(response);
}
2015-09-25 00:25:26 +02:00
Response Response::fromJson(const std::string &json)
{
Json::Reader reader;
Json::Value root;
Response retval;
if (reader.parse(json, root) == false)
throw std::runtime_error("Error parsing JSON");
retval.message = getJsonOrFail<std::string>(root, _messageKey);
const auto code = getJsonOrFail<int>(root, _codeKey);
if (code > Code::RESPONSE_NUM_ITEMS)
throw std::runtime_error("Error code out of range");
retval.code = static_cast<Code>(code);
return retval;
}