Просмотр исходного кода

Added JsonObject::containsKey()

Benoit Blanchon 11 лет назад
Родитель
Сommit
d38131d495

+ 3 - 0
include/ArduinoJson/JsonObject.hpp

@@ -78,6 +78,9 @@ class JsonObject : public Internals::JsonPrintable<JsonObject>,
   // 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);
 

+ 1 - 1
include/ArduinoJson/JsonVariant.hpp

@@ -38,7 +38,7 @@ class JsonVariant : public Internals::JsonPrintable<JsonVariant> {
   }
 
   // Tells weither the variant is valid.
-  bool success() {
+  bool success() const {
     return _type != Internals::JSON_INVALID &&
            _type != Internals::JSON_UNDEFINED;
   }

+ 14 - 0
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"));
+}