JsonNodeSerializer.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "JsonNodeSerializer.h"
  2. #include "EscapedString.h"
  3. #include "JsonNode.h"
  4. using namespace ArduinoJson::Internals;
  5. size_t JsonNodeSerializer::serialize(const JsonNode* node)
  6. {
  7. if (!node) return 0;
  8. switch (node->type)
  9. {
  10. case JSON_OBJECT:
  11. return serializeObject(node);
  12. case JSON_STRING:
  13. return EscapedString::printTo(node->content.asString, _sink);
  14. case JSON_INTEGER:
  15. return _sink.print(node->content.asInteger);
  16. case JSON_BOOLEAN:
  17. return _sink.print(node->content.asBoolean ? "true" : "false");
  18. case JSON_PROXY:
  19. return serialize(node->content.asProxy.target);
  20. }
  21. if (node->type >= JSON_DOUBLE_0_DECIMALS)
  22. {
  23. return _sink.print(node->content.asDouble, node->type - JSON_DOUBLE_0_DECIMALS);
  24. }
  25. return 0;
  26. }
  27. size_t JsonNodeSerializer::serializeObject(const JsonNode* node)
  28. {
  29. size_t n = 0;
  30. n += _sink.write('{');
  31. JsonNode* firstChild = node->content.asContainer.child;
  32. for (JsonNode* child = firstChild; child; child = child->next)
  33. {
  34. n += serializeKeyValue(child);
  35. if (child->next)
  36. {
  37. n += _sink.write(',');
  38. }
  39. }
  40. n += _sink.write('}');
  41. return n;
  42. }
  43. size_t JsonNodeSerializer::serializeKeyValue(JsonNode const* node)
  44. {
  45. const char* childKey = node->content.asKey.key;
  46. JsonNode* childValue = node->content.asKey.value;
  47. return
  48. EscapedString::printTo(childKey, _sink) +
  49. _sink.write(':') +
  50. serialize(childValue);
  51. }