Files
ArduinoJson/src/JsonObject.cpp

68 lines
1.7 KiB
C++
Raw Normal View History

2014-10-23 23:39:22 +02:00
// Copyright Benoit Blanchon 2014
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
#include "ArduinoJson/JsonObject.hpp"
2014-10-16 16:25:42 +02:00
#include <string.h> // for strcmp
2014-10-16 16:25:42 +02:00
#include "ArduinoJson/JsonBuffer.hpp"
#include "ArduinoJson/JsonValue.hpp"
#include "ArduinoJson/Internals/JsonNode.hpp"
#include "ArduinoJson/Internals/StringBuilder.hpp"
2014-10-16 16:25:42 +02:00
2014-10-18 23:05:54 +02:00
using namespace ArduinoJson;
2014-10-16 16:25:42 +02:00
using namespace ArduinoJson::Internals;
2014-10-23 19:54:00 +02:00
JsonValue JsonObject::operator[](char const *key) {
2014-10-25 15:55:58 +02:00
JsonNode *node = getOrCreateValueAt(key);
return JsonValueInternal(node);
2014-10-16 16:25:42 +02:00
}
2014-10-23 19:54:00 +02:00
void JsonObject::remove(char const *key) {
2014-10-25 15:55:58 +02:00
JsonNode *nodeToRemove = getPairAt(key);
if (nodeToRemove) removeChild(nodeToRemove);
2014-10-16 16:25:42 +02:00
}
2014-10-23 19:54:00 +02:00
JsonArray JsonObject::createNestedArray(char const *key) {
2014-10-25 15:55:58 +02:00
JsonNode *node = getOrCreateValueAt(key);
2014-10-16 16:25:42 +02:00
if (node) node->setAsArray(_node->getContainerBuffer());
2014-10-16 16:25:42 +02:00
2014-10-23 19:54:00 +02:00
return JsonArray(node);
2014-10-16 16:25:42 +02:00
}
2014-10-23 19:54:00 +02:00
JsonObject JsonObject::createNestedObject(char const *key) {
2014-10-25 15:55:58 +02:00
JsonNode *node = getOrCreateValueAt(key);
2014-10-16 16:25:42 +02:00
if (node) node->setAsObject(_node->getContainerBuffer());
2014-10-23 19:54:00 +02:00
return JsonObject(node);
2014-10-16 16:25:42 +02:00
}
2014-10-25 15:55:58 +02:00
JsonNode *JsonObject::getPairAt(const char *key) {
for (JsonNode *node = firstChild(); node; node = node->next) {
if (!strcmp(node->getAsObjectKey(), key)) return node;
2014-10-23 19:54:00 +02:00
}
2014-10-25 15:55:58 +02:00
return NULL;
}
JsonNode *JsonObject::getOrCreateValueAt(const char *key) {
JsonNode *existingNode = getPairAt(key);
if (existingNode) return existingNode->getAsObjectValue();
2014-10-23 19:54:00 +02:00
JsonNode *newValueNode = createNode();
if (!newValueNode) return 0;
2014-10-23 19:54:00 +02:00
JsonNode *newKeyNode = createNode();
if (!newKeyNode) return 0;
2014-10-16 16:25:42 +02:00
2014-10-23 19:54:00 +02:00
newKeyNode->setAsObjectKeyValue(key, newValueNode);
2014-10-16 16:25:42 +02:00
2014-10-23 19:54:00 +02:00
addChild(newKeyNode);
2014-10-16 16:25:42 +02:00
2014-10-23 19:54:00 +02:00
return newValueNode;
2014-10-22 21:56:38 +02:00
}