Added JsonObjectIterator

This commit is contained in:
Benoit Blanchon
2014-10-22 21:56:38 +02:00
parent 7e98d136f4
commit 40ac60b941
5 changed files with 121 additions and 1 deletions

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include "JsonContainer.hpp" #include "ArduinoJson/JsonContainer.hpp"
#include "ArduinoJson/JsonObjectIterator.hpp"
namespace ArduinoJson namespace ArduinoJson
{ {
@ -28,6 +29,13 @@ namespace ArduinoJson
return _node && _node->isObject(); return _node && _node->isObject();
} }
JsonObjectIterator begin();
JsonObjectIterator end()
{
return JsonObjectIterator(0);
}
private: private:
Internals::JsonNode* getOrCreateNodeAt(const char* key); Internals::JsonNode* getOrCreateNodeAt(const char* key);
}; };

View File

@ -0,0 +1,52 @@
#pragma once
#include "ArduinoJson/JsonObjectKeyValue.hpp"
namespace ArduinoJson
{
class JsonObject;
class JsonObjectIterator
{
friend class JsonObject;
public:
explicit JsonObjectIterator(Internals::JsonNode* node)
: _node(node)
{
}
const char* key() const
{
return operator*().key();
}
JsonValue value() const
{
return operator*().value();
}
void operator++()
{
_node = _node->next;
}
JsonObjectKeyValue operator*() const
{
return JsonObjectKeyValue(_node);
}
bool operator==(const JsonObjectIterator& other) const
{
return _node == other._node;
}
bool operator!=(const JsonObjectIterator& other) const
{
return _node != other._node;
}
private:
Internals::JsonNode* _node;
};
}

View File

@ -0,0 +1,28 @@
#pragma once
#include "ArduinoJson/JsonValue.hpp"
namespace ArduinoJson
{
class JsonObjectKeyValue
{
public:
explicit JsonObjectKeyValue(Internals::JsonNode* node)
: _node(node)
{
}
const char* key()
{
return _node->getAsObjectKey();
}
JsonValue value()
{
return JsonValue(_node->getAsObjectValue());
}
private:
Internals::JsonNode* _node;
};
}

View File

@ -70,4 +70,9 @@ JsonNode* JsonObject::getOrCreateNodeAt(const char* key)
addChild(newKeyNode); addChild(newKeyNode);
return newValueNode; return newValueNode;
}
JsonObjectIterator JsonObject::begin()
{
return JsonObjectIterator(_node->getContainerChild());
} }

View File

@ -0,0 +1,27 @@
#include <gtest/gtest.h>
#include <ArduinoJson/JsonObject.hpp>
#include <ArduinoJson/StaticJsonBuffer.hpp>
using namespace ArduinoJson;
TEST(JsonObject_Iterator_Test, SimpleTest)
{
StaticJsonBuffer<42> jsonBuffer;
JsonObject object = jsonBuffer.createObject();
object["ab"] = 12;
object["cd"] = 34;
JsonObjectIterator it = object.begin();
JsonObjectIterator end = object.end();
EXPECT_NE(end, it);
EXPECT_STREQ("ab", it.key());
EXPECT_EQ(12, static_cast<int>(it.value()));
++it;
EXPECT_NE(end, it);
EXPECT_STREQ("cd", it.key());
EXPECT_EQ(34, static_cast<int>(it.value()));
++it;
EXPECT_EQ(object.end(), it);
}