issue2129.cpp 976 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2025, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. template <typename T>
  7. class Nullable {
  8. public:
  9. Nullable() : value_{} {}
  10. Nullable(T value) : value_{value} {}
  11. operator T() const {
  12. return value_;
  13. }
  14. operator T&() {
  15. return value_;
  16. }
  17. bool is_valid() const {
  18. return value_ != invalid_value_;
  19. }
  20. T value() const {
  21. return value_;
  22. }
  23. private:
  24. T value_;
  25. static T invalid_value_;
  26. };
  27. template <>
  28. float Nullable<float>::invalid_value_ = std::numeric_limits<float>::lowest();
  29. template <typename T>
  30. void convertToJson(const Nullable<T>& src, JsonVariant dst) {
  31. if (src.is_valid()) {
  32. dst.set(src.value());
  33. } else {
  34. dst.clear();
  35. }
  36. }
  37. TEST_CASE("Issue #2129") {
  38. Nullable<float> nullable_value = Nullable<float>{123.4f};
  39. JsonDocument doc;
  40. doc["value"] = nullable_value;
  41. REQUIRE(doc["value"].as<float>() == Approx(123.4f));
  42. }