CustomWriter.cpp 1016 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2024, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. class CustomWriter {
  7. public:
  8. CustomWriter() {}
  9. CustomWriter(const CustomWriter&) = delete;
  10. CustomWriter& operator=(const CustomWriter&) = delete;
  11. size_t write(uint8_t c) {
  12. str_.append(1, static_cast<char>(c));
  13. return 1;
  14. }
  15. size_t write(const uint8_t* s, size_t n) {
  16. str_.append(reinterpret_cast<const char*>(s), n);
  17. return n;
  18. }
  19. const std::string& str() const {
  20. return str_;
  21. }
  22. private:
  23. std::string str_;
  24. };
  25. TEST_CASE("CustomWriter") {
  26. JsonDocument doc;
  27. JsonArray array = doc.to<JsonArray>();
  28. array.add(4);
  29. array.add(2);
  30. SECTION("serializeJson()") {
  31. CustomWriter writer;
  32. serializeJson(array, writer);
  33. REQUIRE("[4,2]" == writer.str());
  34. }
  35. SECTION("serializeJsonPretty") {
  36. CustomWriter writer;
  37. serializeJsonPretty(array, writer);
  38. REQUIRE("[\r\n 4,\r\n 2\r\n]" == writer.str());
  39. }
  40. }