JsonObject.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if (!checkNodeType(JSON_OBJECT)) return 0;
  42. for (JsonNodeIterator it = beginChildren(); it != endChildren(); ++it)
  43. {
  44. const char* childKey = it->getAsObjectKey();
  45. if (!strcmp(childKey, key))
  46. return it->getAsObjectValue();
  47. }
  48. JsonNode* newValueNode = createNode(JSON_UNDEFINED);
  49. if (!newValueNode) return 0;
  50. JsonNode* newKeyNode = createNode(JSON_KEY_VALUE);
  51. if (!newKeyNode) return 0;
  52. newKeyNode->setAsObjectKeyValue(key, newValueNode);
  53. addChild(newKeyNode);
  54. return newValueNode;
  55. }
  56. JsonNode* JsonObject::createContainerNodeAt(char const* key, JsonNodeType type)
  57. {
  58. JsonNode* node = getOrCreateNodeAt(key);
  59. if (!node) return 0;
  60. node->setAsArray(_node->getContainerBuffer());
  61. return node;
  62. }