JsonObject.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. }