diff --git a/json.cpp b/json.cpp index 0b3e373..5e646a6 100644 --- a/json.cpp +++ b/json.cpp @@ -521,6 +521,17 @@ Json::getString() } } +const std::string& +Json::getString() const +{ + switch (type_) { + case String: + return string_value; + default: + ON_LOGIC_ERROR("JSON value is not a string."); + } +} + std::vector& Json::getArray() { @@ -532,6 +543,17 @@ Json::getArray() } } +const std::vector& +Json::getArray() const +{ + switch (type_) { + case Array: + return array_value; + default: + ON_LOGIC_ERROR("JSON value is not an array."); + } +} + std::map& Json::getObject() { @@ -543,6 +565,17 @@ Json::getObject() } } +const std::map& +Json::getObject() const +{ + switch (type_) { + case Object: + return object_value; + default: + ON_LOGIC_ERROR("JSON value is not an object."); + } +} + void Json::setArray() { @@ -580,6 +613,17 @@ Json::operator[](size_t index) return array_value[index]; } +const Json& +Json::operator[](size_t index) const +{ + if (!isArray()) + ON_LOGIC_ERROR("JSON value is not an array."); + if (index >= array_value.size()) { + ON_LOGIC_ERROR("JSON index not in array."); + } + return array_value[index]; +} + Json& Json::operator[](const std::string& key) { @@ -588,6 +632,17 @@ Json::operator[](const std::string& key) return object_value[key]; } +const Json& +Json::operator[](const std::string& key) const +{ + if (!isObject()) + ON_LOGIC_ERROR("JSON value is not an object."); + auto it = object_value.find(key); + if (it == object_value.end()) + ON_LOGIC_ERROR("JSON object does not contain key."); + return it->second; +} + std::string Json::toString() const { diff --git a/json.h b/json.h index 6bb9087..215e9bf 100644 --- a/json.h +++ b/json.h @@ -190,8 +190,11 @@ class Json double getDouble() const; double getNumber() const; long long getLong() const; + const std::string& getString() const; std::string& getString(); + const std::vector& getArray() const; std::vector& getArray(); + const std::map& getObject() const; std::map& getObject(); bool contains(const std::string&) const; @@ -206,7 +209,9 @@ class Json Json& operator=(Json&&); Json& operator[](size_t); + const Json& operator[](size_t) const; Json& operator[](const std::string&); + const Json& operator[](const std::string&) const; operator std::string() const {