JsonObject.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "JsonObject.h"
  2. #include <string.h> // for strcmp
  3. #include "JsonBuffer.h"
  4. #include "JsonValue.h"
  5. #include "JsonNode.h"
  6. #include "StringBuilder.h"
  7. using namespace ArduinoJson::Internals;
  8. size_t JsonObject::size()
  9. {
  10. JsonNode* firstChild = _node->content.asObject.child;
  11. int size = 0;
  12. for (JsonNode* child = firstChild; child; child = child->next)
  13. {
  14. size++;
  15. }
  16. return size;
  17. }
  18. JsonValue JsonObject::operator[](char const* key)
  19. {
  20. JsonNode* node = getOrCreateNodeAt(key);
  21. return JsonValue(node);
  22. }
  23. bool JsonObject::operator==(JsonObject const& other) const
  24. {
  25. return _node == other._node;
  26. }
  27. JsonNode* JsonObject::getOrCreateNodeAt(char const* key)
  28. {
  29. if (!_node || _node->type != JSON_OBJECT) return 0;
  30. JsonNode* firstChild = _node->content.asObject.child;
  31. JsonNode* lastChild = 0;
  32. for (JsonNode* child = firstChild; child; child = child->next)
  33. {
  34. const char* childKey = child->content.asKey.key;
  35. if (!strcmp(childKey, key))
  36. return child->content.asKey.value;
  37. lastChild = child;
  38. }
  39. JsonBuffer* buffer = _node->content.asObject.buffer;
  40. JsonNode* newValueNode = buffer->createNode(JSON_UNDEFINED);
  41. JsonNode* newKeyNode = buffer->createNode(JSON_KEY);
  42. newKeyNode->content.asKey.key = key;
  43. newKeyNode->content.asKey.value = newValueNode;
  44. if (lastChild)
  45. lastChild->next = newKeyNode;
  46. else
  47. _node->content.asObject.child = newKeyNode;
  48. return newValueNode;
  49. }
  50. size_t JsonObject::printTo(char* buffer, size_t bufferSize) const
  51. {
  52. StringBuilder sb(buffer, bufferSize);
  53. return printTo(sb);
  54. }
  55. size_t JsonObject::printTo(Print& p) const
  56. {
  57. return p.print("{}");
  58. }