JsonObject.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "JsonObject.h"
  2. #include <string.h> // for strcmp
  3. #include "JsonBuffer.h"
  4. #include "JsonValue.h"
  5. #include "Internals/EscapedString.h"
  6. #include "Internals/JsonNode.h"
  7. #include "Internals/StringBuilder.h"
  8. using namespace ArduinoJson::Internals;
  9. JsonValue JsonObject::operator[](char const* key)
  10. {
  11. JsonNode* node = getOrCreateNodeAt(key);
  12. return JsonValue(node);
  13. }
  14. void JsonObject::remove(char const* key)
  15. {
  16. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  17. {
  18. const char* childKey = it->getAsObjectKey();
  19. if (!strcmp(childKey, key))
  20. {
  21. removeChild(*it);
  22. }
  23. }
  24. }
  25. JsonArray JsonObject::createNestedArray(char const* key)
  26. {
  27. JsonNode* node = getOrCreateNodeAt(key);
  28. if (node)
  29. node->setAsArray(_node->getContainerBuffer());
  30. return JsonArray(node);
  31. }
  32. JsonObject JsonObject::createNestedObject(char const* key)
  33. {
  34. JsonNode* node = getOrCreateNodeAt(key);
  35. if (node)
  36. node->setAsObject(_node->getContainerBuffer());
  37. return JsonObject(node);
  38. }
  39. JsonNode* JsonObject::getOrCreateNodeAt(const char* key)
  40. {
  41. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  42. {
  43. const char* childKey = it->getAsObjectKey();
  44. if (!strcmp(childKey, key))
  45. return it->getAsObjectValue();
  46. }
  47. JsonNode* newValueNode = createNode();
  48. if (!newValueNode) return 0;
  49. JsonNode* newKeyNode = createNode();
  50. if (!newKeyNode) return 0;
  51. newKeyNode->setAsObjectKeyValue(key, newValueNode);
  52. addChild(newKeyNode);
  53. return newValueNode;
  54. }
  55. JsonNode* JsonObject::createContainerNodeAt(char const* key, JsonNodeType type)
  56. {
  57. JsonNode* node = getOrCreateNodeAt(key);
  58. if (!node) return 0;
  59. node->setAsArray(_node->getContainerBuffer());
  60. return node;
  61. }