diff --git a/srcs/JsonObject.cpp b/srcs/JsonObject.cpp index 61d88b60..e7fe07b1 100644 --- a/srcs/JsonObject.cpp +++ b/srcs/JsonObject.cpp @@ -33,17 +33,15 @@ void JsonObject::remove(char const* key) } } +JsonArray JsonObject::createNestedArray(char const* key) +{ + JsonNode* node = createContainerNodeAt(key, JSON_ARRAY); + return JsonArray(node); +} + JsonObject JsonObject::createNestedObject(char const* key) { - JsonNode* node = getOrCreateNodeAt(key); - - if (node) - { - node->type = JSON_OBJECT; - node->content.asContainer.child = 0; - node->content.asContainer.buffer = _node->content.asContainer.buffer; - } - + JsonNode* node = createContainerNodeAt(key, JSON_OBJECT); return JsonObject(node); } @@ -72,3 +70,15 @@ JsonNode* JsonObject::getOrCreateNodeAt(const char* key) return newValueNode; } + +JsonNode* JsonObject::createContainerNodeAt(char const* key, JsonNodeType type) +{ + JsonNode* node = getOrCreateNodeAt(key); + if (!node) return 0; + + node->type = type; + node->content.asContainer.child = 0; + node->content.asContainer.buffer = _node->content.asContainer.buffer; + + return node; +} \ No newline at end of file diff --git a/srcs/JsonObject.h b/srcs/JsonObject.h index 0b631211..7af15c08 100644 --- a/srcs/JsonObject.h +++ b/srcs/JsonObject.h @@ -2,6 +2,7 @@ #include "JsonContainer.h" +class JsonArray; class JsonValue; struct JsonNode; @@ -21,8 +22,10 @@ public: JsonValue operator[](const char* key); void remove(const char* key); + JsonArray createNestedArray(const char* key); JsonObject createNestedObject(const char* key); private: - JsonNode* getOrCreateNodeAt(char const* key); + JsonNode* getOrCreateNodeAt(const char* key); + JsonNode* createContainerNodeAt(const char* key, JsonNodeType type); }; \ No newline at end of file diff --git a/tests/JsonObject_PrettyPrintTo_Tests.cpp b/tests/JsonObject_PrettyPrintTo_Tests.cpp index 3837985e..83abbff1 100644 --- a/tests/JsonObject_PrettyPrintTo_Tests.cpp +++ b/tests/JsonObject_PrettyPrintTo_Tests.cpp @@ -57,33 +57,33 @@ TEST_F(JsonObject_PrettyPrintTo_Tests, TwoMembers) "}"); } -TEST_F(JsonObject_PrettyPrintTo_Tests, EmptyNestedObjects) +TEST_F(JsonObject_PrettyPrintTo_Tests, EmptyNestedContainers) { object.createNestedObject("key1"); - object.createNestedObject("key2"); + object.createNestedArray("key2"); outputMustBe( "{\r\n" " \"key1\": {},\r\n" - " \"key2\": {}\r\n" + " \"key2\": []\r\n" "}"); } -TEST_F(JsonObject_PrettyPrintTo_Tests, NestedObjects) +TEST_F(JsonObject_PrettyPrintTo_Tests, NestedContainers) { JsonObject nested1 = object.createNestedObject("key1"); nested1["a"] = 1; - JsonObject nested2 = object.createNestedObject("key2"); - nested2["b"] = 2; + JsonArray nested2 = object.createNestedArray("key2"); + nested2.add(2); outputMustBe( "{\r\n" " \"key1\": {\r\n" " \"a\": 1\r\n" " },\r\n" - " \"key2\": {\r\n" - " \"b\": 2\r\n" - " }\r\n" + " \"key2\": [\r\n" + " 2\r\n" + " ]\r\n" "}"); } \ No newline at end of file