JsonWriter.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright Benoit Blanchon 2014-2015
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://github.com/bblanchon/ArduinoJson
  6. #pragma once
  7. #include "../Arduino/Print.hpp"
  8. #include "QuotedString.hpp"
  9. namespace ArduinoJson {
  10. namespace Internals {
  11. // Writes the JSON tokens to a Print implementation
  12. // This class is used by:
  13. // - JsonArray::writeTo()
  14. // - JsonObject::writeTo()
  15. // - JsonVariant::writeTo()
  16. // Its derived by PrettyJsonWriter that overrides some members to add
  17. // indentation.
  18. class JsonWriter {
  19. public:
  20. explicit JsonWriter(Print &sink) : _sink(sink), _length(0) {}
  21. // Returns the number of bytes sent to the Print implementation.
  22. // This is very handy for implementations of printTo() that must return the
  23. // number of bytes written.
  24. size_t bytesWritten() { return _length; }
  25. void beginArray() { write('['); }
  26. void endArray() { write(']'); }
  27. void beginObject() { write('{'); }
  28. void endObject() { write('}'); }
  29. void writeColon() { write(':'); }
  30. void writeComma() { write(','); }
  31. void writeString(const char *value) {
  32. _length += QuotedString::printTo(value, _sink);
  33. }
  34. void writeLong(long value) { _length += _sink.print(value); }
  35. void writeBoolean(bool value) {
  36. _length += _sink.print(value ? "true" : "false");
  37. }
  38. void writeDouble(double value, uint8_t decimals) {
  39. _length += _sink.print(value, decimals);
  40. }
  41. protected:
  42. void write(char c) { _length += _sink.write(c); }
  43. void write(const char *s) { _length += _sink.print(s); }
  44. Print &_sink;
  45. size_t _length;
  46. private:
  47. JsonWriter &operator=(const JsonWriter &); // cannot be assigned
  48. };
  49. }
  50. }