From b9dc2f5ee1fa38cba2c7c5b6f05748720eb8981c Mon Sep 17 00:00:00 2001 From: Ralf Ramsauer Date: Fri, 25 Sep 2015 00:38:34 +0200 Subject: [PATCH] Improved Clientmessage - Added Clientmessage::fromJson - Improved JSON key handling --- doorlockd/src/clientmessage.cpp | 42 +++++++++++++++++++++++++++++---- doorlockd/src/clientmessage.h | 9 +++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/doorlockd/src/clientmessage.cpp b/doorlockd/src/clientmessage.cpp index df94e62..aad10ba 100644 --- a/doorlockd/src/clientmessage.cpp +++ b/doorlockd/src/clientmessage.cpp @@ -1,6 +1,12 @@ #include #include "clientmessage.h" +#include "util.h" + +const std::string Clientmessage::_tokenKey = "token"; +const std::string Clientmessage::_unlockButtonKey = "unlockButton"; +const std::string Clientmessage::_lockButtonKey = "lockButton"; +const std::string Clientmessage::_emergencyUnlockKey = "emergencyUnlock"; Clientmessage::Clientmessage(std::string token, Doormessage doormessage) : @@ -14,10 +20,38 @@ std::string Clientmessage::toJson() const Json::StyledWriter writer; Json::Value message; - message["token"] = _token; - message["unlockButton"] = _doormessage.isUnlockButton; - message["lockButton"] = _doormessage.isLockButton; - message["emergencyUnlock"] = _doormessage.isEmergencyUnlock; + message[_tokenKey] = _token; + message[_unlockButtonKey] = _doormessage.isUnlockButton; + message[_lockButtonKey] = _doormessage.isLockButton; + message[_emergencyUnlockKey] = _doormessage.isEmergencyUnlock; return writer.write(message); } + +const std::string& Clientmessage::token() const +{ + return _token; +} + +const Doormessage& Clientmessage::doormessage() const +{ + return _doormessage; +} + +Clientmessage Clientmessage::fromJson(const std::string &json) +{ + Json::Reader reader; + Json::Value root; + std::string token; + Doormessage doormessage; + + if (reader.parse(json, root) == false) + throw std::runtime_error("Error parsing JSON"); + + token = getJsonOrFail(root, _tokenKey); + doormessage.isLockButton = getJsonOrFail(root, _lockButtonKey); + doormessage.isUnlockButton = getJsonOrFail(root, _unlockButtonKey); + doormessage.isEmergencyUnlock = getJsonOrFail(root, _emergencyUnlockKey); + + return Clientmessage(token, doormessage); +} diff --git a/doorlockd/src/clientmessage.h b/doorlockd/src/clientmessage.h index cb76875..bd05814 100644 --- a/doorlockd/src/clientmessage.h +++ b/doorlockd/src/clientmessage.h @@ -13,12 +13,21 @@ public: Clientmessage(std::string token, Doormessage doormessage); + static Clientmessage fromJson(const std::string &json); std::string toJson() const; + const std::string& token() const; + const Doormessage& doormessage() const; + private: std::string _token; Doormessage _doormessage; + + static const std::string _tokenKey; + const static std::string _unlockButtonKey; + const static std::string _lockButtonKey; + const static std::string _emergencyUnlockKey; }; #endif