JsonNode.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #include "JsonNode.h"
  2. #include "JsonWriter.h"
  3. #include "../JsonArray.h"
  4. #include "../JsonObject.h"
  5. void JsonNode::writeTo(JsonWriter& writer)
  6. {
  7. switch (type)
  8. {
  9. case JSON_ARRAY:
  10. writeArrayTo(writer);
  11. break;
  12. case JSON_OBJECT:
  13. writeObjectTo(writer);
  14. break;
  15. case JSON_STRING:
  16. writer.writeString(content.asString);
  17. break;
  18. case JSON_LONG:
  19. writer.writeInteger(content.asInteger);
  20. break;
  21. case JSON_BOOLEAN:
  22. writer.writeBoolean(content.asBoolean);
  23. break;
  24. default: // >= JSON_DOUBLE_0_DECIMALS
  25. writer.writeDouble(content.asDouble, type - JSON_DOUBLE_0_DECIMALS);
  26. break;
  27. }
  28. }
  29. void JsonNode::addChildToContainer(JsonNode* childToAdd)
  30. {
  31. if (type != JSON_ARRAY && type != JSON_OBJECT) return;
  32. JsonNode* lastChild = content.asContainer.child;
  33. if (!lastChild)
  34. {
  35. content.asContainer.child = childToAdd;
  36. return;
  37. }
  38. while (lastChild->next)
  39. lastChild = lastChild->next;
  40. lastChild->next = childToAdd;
  41. }
  42. void JsonNode::removeChildFromContainer(JsonNode* childToRemove)
  43. {
  44. if (type != JSON_ARRAY && type != JSON_OBJECT) return;
  45. if (content.asContainer.child == childToRemove)
  46. {
  47. content.asContainer.child = childToRemove->next;
  48. return;
  49. }
  50. for (JsonNode* child = content.asContainer.child; child; child = child->next)
  51. {
  52. if (child->next == childToRemove)
  53. child->next = childToRemove->next;
  54. }
  55. }
  56. void JsonNode::writeArrayTo(JsonWriter& writer)
  57. {
  58. JsonNode* child = content.asContainer.child;
  59. if (child)
  60. {
  61. writer.beginArray();
  62. while (true)
  63. {
  64. child->writeTo(writer);
  65. child = child->next;
  66. if (!child) break;
  67. writer.writeComma();
  68. }
  69. writer.endArray();
  70. }
  71. else
  72. {
  73. writer.writeEmptyArray();
  74. }
  75. }
  76. void JsonNode::writeObjectTo(JsonWriter& writer)
  77. {
  78. JsonNode* child = content.asContainer.child;
  79. if (child)
  80. {
  81. writer.beginObject();
  82. while (true)
  83. {
  84. writer.writeString(child->content.asKey.key);
  85. writer.writeColon();
  86. child->content.asKey.value->writeTo(writer);
  87. child = child->next;
  88. if (!child) break;
  89. writer.writeComma();
  90. }
  91. writer.endObject();
  92. }
  93. else
  94. {
  95. writer.writeEmptyObject();
  96. }
  97. }