diff --git a/include/ArduinoJson/JsonObject.hpp b/include/ArduinoJson/JsonObject.hpp index b965970a..9c264543 100644 --- a/include/ArduinoJson/JsonObject.hpp +++ b/include/ArduinoJson/JsonObject.hpp @@ -78,6 +78,9 @@ class JsonObject : public Internals::JsonPrintable, // This is a shortcut for JsonBuffer::createObject() and JsonObject::add(). JsonObject &createNestedObject(key_type key); + // Tells weither the specified key is present and associated with a value. + bool containsKey(key_type key) const { return at(key).success(); } + // Removes the specified key and the associated value. void remove(key_type key); diff --git a/include/ArduinoJson/JsonVariant.hpp b/include/ArduinoJson/JsonVariant.hpp index 3f49b0fa..ba9598d1 100644 --- a/include/ArduinoJson/JsonVariant.hpp +++ b/include/ArduinoJson/JsonVariant.hpp @@ -38,7 +38,7 @@ class JsonVariant : public Internals::JsonPrintable { } // Tells weither the variant is valid. - bool success() { + bool success() const { return _type != Internals::JSON_INVALID && _type != Internals::JSON_UNDEFINED; } diff --git a/test/JsonObject_Container_Tests.cpp b/test/JsonObject_Container_Tests.cpp index 6e75cba6..24a3893e 100644 --- a/test/JsonObject_Container_Tests.cpp +++ b/test/JsonObject_Container_Tests.cpp @@ -114,3 +114,17 @@ TEST_F(JsonObject_Container_Tests, CanStoreInnerObjects) { EXPECT_EQ(&innerObject1, &object["hello"].asObject()); EXPECT_EQ(&innerObject2, &object["world"].asObject()); } + +TEST_F(JsonObject_Container_Tests, ContainsKeyReturnFalseForNonExistingKey) { + EXPECT_FALSE(object.containsKey("hello")); +} + +TEST_F(JsonObject_Container_Tests, ContainsKeyReturnTrueForDefinedValue) { + object.add("hello", 42); + EXPECT_TRUE(object.containsKey("hello")); +} + +TEST_F(JsonObject_Container_Tests, ContainsKeyReturnFalseForUndefinedValue) { + object.add("hello"); + EXPECT_FALSE(object.containsKey("hello")); +}