JsonVariant.ipp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright Benoit Blanchon 2014-2016
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://github.com/bblanchon/ArduinoJson
  6. // If you like this project, please add a star!
  7. #pragma once
  8. #include "Configuration.hpp"
  9. #include "JsonVariant.hpp"
  10. #include "Internals/Parse.hpp"
  11. #include <string.h>
  12. namespace ArduinoJson {
  13. inline JsonVariant::JsonVariant(bool value) {
  14. using namespace Internals;
  15. _type = JSON_BOOLEAN;
  16. _content.asInteger = static_cast<JsonInteger>(value);
  17. }
  18. inline JsonVariant::JsonVariant(const char *value) {
  19. _type = Internals::JSON_STRING;
  20. _content.asString = value;
  21. }
  22. inline JsonVariant::JsonVariant(RawJson value) {
  23. _type = Internals::JSON_UNPARSED;
  24. _content.asString = value;
  25. }
  26. inline JsonVariant::JsonVariant(JsonArray &array) {
  27. _type = Internals::JSON_ARRAY;
  28. _content.asArray = &array;
  29. }
  30. inline JsonVariant::JsonVariant(JsonObject &object) {
  31. _type = Internals::JSON_OBJECT;
  32. _content.asObject = &object;
  33. }
  34. template <typename T>
  35. inline T JsonVariant::invalid() {
  36. return T();
  37. }
  38. inline Internals::JsonInteger JsonVariant::asInteger() const {
  39. if (_type == Internals::JSON_INTEGER || _type == Internals::JSON_BOOLEAN)
  40. return _content.asInteger;
  41. if (_type >= Internals::JSON_FLOAT_0_DECIMALS)
  42. return static_cast<Internals::JsonInteger>(_content.asFloat);
  43. if ((_type == Internals::JSON_STRING || _type == Internals::JSON_UNPARSED) &&
  44. _content.asString) {
  45. if (!strcmp("true", _content.asString)) return 1;
  46. return Internals::parse<Internals::JsonInteger>(_content.asString);
  47. }
  48. return 0L;
  49. }
  50. #if ARDUINOJSON_ENABLE_STD_STREAM
  51. inline std::ostream &operator<<(std::ostream &os, const JsonVariant &source) {
  52. return source.printTo(os);
  53. }
  54. #endif
  55. } // namespace ArduinoJson