JsonObject.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "JsonBuffer.h"
  2. #include "JsonObject.h"
  3. #include "JsonValue.h"
  4. #include "JsonNode.h"
  5. #include <string.h> // for strcmp
  6. //JsonValue& JsonObject::operator[](char const* key)
  7. //{
  8. // addNodeAt(key, innerObject._node);
  9. // return innerObject;
  10. //}
  11. //
  12. //void JsonObject::addNodeAt(const char* key, JsonNode& node)
  13. //{
  14. // JsonNode& keyNode = _buffer.createNode();
  15. // keyNode.becomeKey(key, node);
  16. // appendChild(keyNode);
  17. //}
  18. //
  19. //void JsonObject::appendChild(JsonNode& newChild)
  20. //{
  21. // JsonNode* lastChild = _node.asObjectNode.child;
  22. // while (lastChild->next)
  23. // {
  24. // lastChild = lastChild->next;
  25. // }
  26. //
  27. // if (lastChild)
  28. // lastChild->next = &newChild;
  29. // else
  30. // _node.asObjectNode.child = &newChild;
  31. //}
  32. size_t JsonObject::size()
  33. {
  34. JsonNode* firstChild = _node->content.asObject.child;
  35. int size = 0;
  36. for (JsonNode* child = firstChild; child; child = child->next)
  37. {
  38. size++;
  39. }
  40. return size;
  41. }
  42. JsonValue JsonObject::operator[](char const* key)
  43. {
  44. JsonNode* node = getOrCreateNodeAt(key);
  45. return JsonValue(node);
  46. }
  47. bool JsonObject::operator==(JsonObject const& other) const
  48. {
  49. return _node == other._node;
  50. }
  51. JsonNode* JsonObject::getOrCreateNodeAt(char const* key)
  52. {
  53. if (!_node || _node->type != JSON_OBJECT) return 0;
  54. JsonNode* firstChild = _node->content.asObject.child;
  55. JsonNode* lastChild = 0;
  56. for (JsonNode* child = firstChild; child; child = child->next)
  57. {
  58. const char* childKey = child->content.asKey.key;
  59. if (!strcmp(childKey, key))
  60. return child->content.asKey.value;
  61. lastChild = child;
  62. }
  63. JsonBuffer* buffer = _node->content.asObject.buffer;
  64. JsonNode* newValueNode = buffer->createNode(JSON_UNDEFINED);
  65. JsonNode* newKeyNode = buffer->createNode(JSON_KEY);
  66. newKeyNode->content.asKey.key = key;
  67. newKeyNode->content.asKey.value = newValueNode;
  68. if (lastChild)
  69. lastChild->next = newKeyNode;
  70. else
  71. _node->content.asObject.child = newKeyNode;
  72. return newValueNode;
  73. }