JsonObject.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "JsonBuffer.h"
  2. #include "JsonObject.h"
  3. #include "JsonValue.h"
  4. #include "JsonNode.h"
  5. #include <string.h>
  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.asObjectNode.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. JsonNode* JsonObject::getOrCreateNodeAt(char const* key)
  48. {
  49. if (!_node || _node->type != JSON_OBJECT) return 0;
  50. JsonNode* firstChild = _node->content.asObjectNode.child;
  51. JsonNode* lastChild = 0;
  52. for (JsonNode* child = firstChild; child; child = child->next)
  53. {
  54. const char* childKey = child->content.asKey.key;
  55. if (!strcmp(childKey, key))
  56. return child->content.asKey.value;
  57. lastChild = child;
  58. }
  59. JsonNode* newValueNode = _buffer->createNode(JSON_UNDEFINED);
  60. JsonNode* newKeyNode = _buffer->createNode(JSON_KEY);
  61. newKeyNode->content.asKey.key = key;
  62. newKeyNode->content.asKey.value = newValueNode;
  63. if (lastChild)
  64. lastChild->next = newKeyNode;
  65. else
  66. _node->content.asObjectNode.child = newKeyNode;
  67. return newValueNode;
  68. }