JsonObject.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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/JsonNodeSerializer.h"
  8. #include "Internals/StringBuilder.h"
  9. using namespace ArduinoJson::Internals;
  10. size_t JsonObject::size()
  11. {
  12. JsonNode* firstChild = _node->content.asContainer.child;
  13. int size = 0;
  14. for (JsonNode* child = firstChild; child; child = child->next)
  15. {
  16. size++;
  17. }
  18. return size;
  19. }
  20. JsonValue JsonObject::operator[](char const* key)
  21. {
  22. JsonNode* node = getOrCreateNodeAt(key);
  23. return JsonValue(node);
  24. }
  25. void JsonObject::remove(char const* key)
  26. {
  27. JsonNode* firstChild = _node->content.asContainer.child;
  28. JsonNode* lastChild = 0;
  29. for (JsonNode* child = firstChild; child; child = child->next)
  30. {
  31. const char* childKey = child->content.asKey.key;
  32. if (!strcmp(childKey, key))
  33. {
  34. if (lastChild)
  35. lastChild->next = child->next;
  36. else
  37. _node->content.asContainer.child = child->next;
  38. }
  39. lastChild = child;
  40. }
  41. }
  42. bool JsonObject::operator==(JsonObject const& other) const
  43. {
  44. return _node == other._node;
  45. }
  46. JsonNode* JsonObject::getOrCreateNodeAt(char const* key)
  47. {
  48. if (!_node || _node->type != JSON_OBJECT) return 0;
  49. JsonNode* firstChild = _node->content.asContainer.child;
  50. JsonNode* lastChild = 0;
  51. for (JsonNode* child = firstChild; child; child = child->next)
  52. {
  53. const char* childKey = child->content.asKey.key;
  54. if (!strcmp(childKey, key))
  55. return child->content.asKey.value;
  56. lastChild = child;
  57. }
  58. JsonBuffer* buffer = _node->content.asContainer.buffer;
  59. JsonNode* newValueNode = buffer->createNode(JSON_UNDEFINED);
  60. if (!newValueNode) return 0;
  61. JsonNode* newKeyNode = buffer->createNode(JSON_KEY);
  62. if (!newKeyNode) return 0;
  63. newKeyNode->content.asKey.key = key;
  64. newKeyNode->content.asKey.value = newValueNode;
  65. if (lastChild)
  66. lastChild->next = newKeyNode;
  67. else
  68. _node->content.asContainer.child = newKeyNode;
  69. return newValueNode;
  70. }