Browse Source

Added `JsonDocument::containsKey()` (issue #938)

Benoit Blanchon 6 years ago
parent
commit
c8e49a7e4e

+ 1 - 0
CHANGELOG.md

@@ -9,6 +9,7 @@ HEAD
    - `as<T>()` returns `0` if the integer `T` overflows
    - `is<T>()` returns `false` if the integer `T` overflows
 * Added `BasicJsonDocument` to support custom allocator (issue #876)
+* Added `JsonDocument::containsKey()` (issue #938)
 
 v6.9.1 (2019-03-01)
 ------

+ 15 - 0
src/ArduinoJson/Document/JsonDocument.hpp

@@ -124,6 +124,21 @@ class JsonDocument : public Visitable {
     return getOrAddMember(key).template to<ObjectRef>();
   }
 
+  // containsKey(char*) const
+  // containsKey(const char*) const
+  // containsKey(const __FlashStringHelper*) const
+  template <typename TChar>
+  bool containsKey(TChar* key) const {
+    return as<ObjectRef>().containsKey(key);
+  }
+
+  // containsKey(const std::string&) const
+  // containsKey(const String&) const
+  template <typename TString>
+  bool containsKey(const TString& key) const {
+    return as<ObjectRef>().containsKey(key);
+  }
+
   // operator[](const std::string&)
   // operator[](const String&)
   template <typename TString>

+ 1 - 0
test/JsonDocument/CMakeLists.txt

@@ -5,6 +5,7 @@
 add_executable(JsonDocumentTests
 	add.cpp
 	BasicJsonDocument.cpp
+	containsKey.cpp
 	createNested.cpp
 	DynamicJsonDocument.cpp
 	isNull.cpp

+ 44 - 0
test/JsonDocument/containsKey.cpp

@@ -0,0 +1,44 @@
+// ArduinoJson - arduinojson.org
+// Copyright Benoit Blanchon 2014-2019
+// MIT License
+
+#include <ArduinoJson.h>
+#include <catch.hpp>
+
+TEST_CASE("JsonDocument::containsKey()") {
+  DynamicJsonDocument doc(4096);
+
+  SECTION("returns true on object") {
+    doc["hello"] = "world";
+
+    REQUIRE(doc.containsKey("hello") == true);
+  }
+
+  SECTION("returns true when value is null") {
+    doc["hello"] = static_cast<const char*>(0);
+
+    REQUIRE(doc.containsKey("hello") == true);
+  }
+
+  SECTION("returns true when key is a std::string") {
+    doc["hello"] = "world";
+
+    REQUIRE(doc.containsKey(std::string("hello")) == true);
+  }
+
+  SECTION("returns false  on object") {
+    doc["world"] = "hello";
+
+    REQUIRE(doc.containsKey("hello") == false);
+  }
+
+  SECTION("returns false on array") {
+    doc.add("hello");
+
+    REQUIRE(doc.containsKey("hello") == false);
+  }
+
+  SECTION("returns false on null") {
+    REQUIRE(doc.containsKey("hello") == false);
+  }
+}