Files
ArduinoJson/src/JsonObject.cpp

86 lines
2.1 KiB
C++
Raw Normal View History

2015-02-07 16:05:48 +01:00
// Copyright Benoit Blanchon 2014-2015
2014-10-23 23:39:22 +02:00
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
2014-11-03 18:35:22 +01:00
#include "../include/ArduinoJson/JsonObject.hpp"
2014-10-29 14:24:34 +01:00
#include <string.h> // for strcmp
2014-11-03 18:35:22 +01:00
#include "../include/ArduinoJson/Internals/StringBuilder.hpp"
2014-11-04 10:01:21 +01:00
#include "../include/ArduinoJson/JsonArray.hpp"
#include "../include/ArduinoJson/JsonBuffer.hpp"
2014-10-16 16:25:42 +02:00
2014-10-18 23:05:54 +02:00
using namespace ArduinoJson;
2014-10-29 14:24:34 +01:00
using namespace ArduinoJson::Internals;
2014-10-16 16:25:42 +02:00
2014-10-30 14:03:33 +01:00
JsonObject JsonObject::_invalid(NULL);
2014-11-04 09:51:25 +01:00
JsonVariant &JsonObject::at(const char *key) {
node_type *node = getNodeAt(key);
return node ? node->content.value : JsonVariant::invalid();
}
2014-11-04 09:51:25 +01:00
const JsonVariant &JsonObject::at(const char *key) const {
node_type *node = getNodeAt(key);
return node ? node->content.value : JsonVariant::invalid();
}
2014-11-04 09:51:25 +01:00
JsonVariant &JsonObject::operator[](const char *key) {
2014-11-08 21:37:02 +01:00
// try to find an existing node
node_type *node = getNodeAt(key);
2014-11-08 21:37:02 +01:00
// not fount => create a new one
if (!node) {
node = createNode();
if (!node) return JsonVariant::invalid();
2014-11-08 21:37:02 +01:00
node->content.key = key;
addNode(node);
}
2014-11-08 21:37:02 +01:00
return node->content.value;
2014-10-29 14:24:34 +01:00
}
void JsonObject::remove(char const *key) { removeNode(getNodeAt(key)); }
JsonArray &JsonObject::createNestedArray(char const *key) {
if (!_buffer) return JsonArray::invalid();
JsonArray &array = _buffer->createArray();
add(key, array);
return array;
2014-10-16 16:25:42 +02:00
}
2014-10-29 14:24:34 +01:00
JsonObject &JsonObject::createNestedObject(const char *key) {
if (!_buffer) return JsonObject::invalid();
JsonObject &object = _buffer->createObject();
add(key, object);
return object;
}
JsonObject::node_type *JsonObject::getNodeAt(const char *key) const {
for (node_type *node = _firstNode; node; node = node->next) {
if (!strcmp(node->content.key, key)) return node;
2014-10-29 14:24:34 +01:00
}
return NULL;
}
void JsonObject::writeTo(JsonWriter &writer) const {
writer.beginObject();
2014-10-29 14:24:34 +01:00
const node_type *node = _firstNode;
while (node) {
writer.writeString(node->content.key);
writer.writeColon();
node->content.value.writeTo(writer);
2014-10-29 14:24:34 +01:00
node = node->next;
if (!node) break;
2014-10-29 14:24:34 +01:00
writer.writeComma();
2014-10-29 14:24:34 +01:00
}
writer.endObject();
2014-10-22 21:56:38 +02:00
}