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

Added ability to set a nested value like this: `root["A"]["B"] = "C"` (issue #352)

Benoit Blanchon 9 лет назад
Родитель
Сommit
1f3e227a8b

+ 1 - 0
CHANGELOG.md

@@ -4,6 +4,7 @@ ArduinoJson: change log
 HEAD
 ----
 
+* Added ability to set a nested value like this: `root["A"]["B"] = "C"` (issue #352)
 * Renamed `*.ipp` to `*Impl.hpp` because they were ignored by Arduino IDE (issue #396)
 
 v5.7.2

+ 5 - 0
include/ArduinoJson/JsonArraySubscript.hpp

@@ -67,6 +67,11 @@ inline JsonArraySubscript JsonArray::operator[](size_t index) {
   return JsonArraySubscript(*this, index);
 }
 
+template <typename TImplem>
+inline JsonArraySubscript JsonVariantBase<TImplem>::operator[](int index) {
+  return asArray()[index];
+}
+
 template <typename TImplem>
 inline const JsonArraySubscript JsonVariantBase<TImplem>::operator[](
     int index) const {

+ 8 - 0
include/ArduinoJson/JsonVariantBase.hpp

@@ -71,6 +71,7 @@ class JsonVariantBase : public Internals::JsonPrintable<TImpl> {
   // Returns the element at specified index if the variant is an array.
   // Returns JsonVariant::invalid() if the variant is not an array.
   FORCE_INLINE const JsonArraySubscript operator[](int index) const;
+  FORCE_INLINE JsonArraySubscript operator[](int index);
 
   // Mimics an object.
   // Returns the value associated with the specified key if the variant is
@@ -83,6 +84,13 @@ class JsonVariantBase : public Internals::JsonPrintable<TImpl> {
       operator[](const TString &key) const {
     return asObject()[key];
   }
+  template <typename TString>
+  FORCE_INLINE
+      typename TypeTraits::EnableIf<Internals::StringFuncs<TString>::has_equals,
+                                    JsonObjectSubscript<TString> >::type
+      operator[](const TString &key) {
+    return asObject()[key];
+  }
 
  private:
   const TImpl *impl() const {

+ 22 - 0
test/JsonVariant_Subscript_Tests.cpp

@@ -59,3 +59,25 @@ TEST_F(JsonVariant_Subscript_Tests, String) {
   EXPECT_FALSE(_variant["0"].success());
   EXPECT_FALSE(_variant[0].success());
 }
+
+TEST_F(JsonVariant_Subscript_Tests, ObjectSetValue) {
+  _variant = _jsonBuffer.createObject();
+  _variant["hello"] = "world";
+  EXPECT_EQ(1, _variant.size());
+  EXPECT_STREQ("world", _variant["hello"]);
+}
+
+TEST_F(JsonVariant_Subscript_Tests, ArraySetValue) {
+  _variant = _jsonBuffer.parseArray("[\"hello\"]");
+  _variant[0] = "world";
+  EXPECT_EQ(1, _variant.size());
+  EXPECT_STREQ("world", _variant[0]);
+}
+
+TEST_F(JsonVariant_Subscript_Tests, NestedObjectSetValue) {
+  _variant = _jsonBuffer.parseArray("[{}]");
+  _variant[0]["hello"] = "world";
+  EXPECT_EQ(1, _variant.size());
+  EXPECT_EQ(1, _variant[0].size());
+  EXPECT_STREQ("world", _variant[0]["hello"]);
+}