JsonValue.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright Benoit Blanchon 2014
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://github.com/bblanchon/ArduinoJson
  6. #include "ArduinoJson/JsonValue.hpp"
  7. #include "ArduinoJson/JsonArray.hpp"
  8. #include "ArduinoJson/JsonObject.hpp"
  9. #include "ArduinoJson/Internals/JsonWriter.hpp"
  10. using namespace ArduinoJson;
  11. using namespace ArduinoJson::Internals;
  12. JsonValue::operator JsonArray &() const {
  13. return _type == JSON_ARRAY ? *_content.asArray : JsonArray::invalid();
  14. }
  15. JsonValue::operator JsonObject &() const {
  16. return _type == JSON_OBJECT ? *_content.asObject : JsonObject::invalid();
  17. }
  18. JsonValue::operator bool() const {
  19. return _type == JSON_BOOLEAN ? _content.asBoolean : false;
  20. }
  21. JsonValue::operator const char *() const {
  22. return _type == JSON_STRING ? _content.asString : NULL;
  23. }
  24. JsonValue::operator double() const {
  25. return _type >= JSON_DOUBLE_0_DECIMALS ? _content.asDouble : 0;
  26. }
  27. JsonValue::operator long() const {
  28. return _type == JSON_LONG ? _content.asInteger : 0;
  29. }
  30. void JsonValue::set(bool value) {
  31. if (_type == JSON_INVALID) return;
  32. _type = Internals::JSON_BOOLEAN;
  33. _content.asBoolean = value;
  34. }
  35. void JsonValue::set(const char *value) {
  36. if (_type == JSON_INVALID) return;
  37. _type = JSON_STRING;
  38. _content.asString = value;
  39. }
  40. void JsonValue::set(double value, int decimals) {
  41. if (_type == JSON_INVALID) return;
  42. _type = static_cast<JsonValueType>(JSON_DOUBLE_0_DECIMALS + decimals);
  43. _content.asDouble = value;
  44. }
  45. void JsonValue::set(long value) {
  46. if (_type == JSON_INVALID) return;
  47. _type = JSON_LONG;
  48. _content.asInteger = value;
  49. }
  50. void JsonValue::set(JsonArray &array) {
  51. if (_type == JSON_INVALID) return;
  52. _type = JSON_ARRAY;
  53. _content.asArray = &array;
  54. }
  55. void JsonValue::set(JsonObject &object) {
  56. if (_type == JSON_INVALID) return;
  57. _type = JSON_OBJECT;
  58. _content.asObject = &object;
  59. }
  60. void JsonValue::writeTo(JsonWriter &writer) const {
  61. switch (_type) {
  62. case JSON_ARRAY:
  63. _content.asArray->writeTo(writer);
  64. break;
  65. case JSON_OBJECT:
  66. _content.asObject->writeTo(writer);
  67. break;
  68. case JSON_STRING:
  69. writer.writeString(_content.asString);
  70. break;
  71. case JSON_LONG:
  72. writer.writeInteger(_content.asInteger);
  73. break;
  74. case JSON_BOOLEAN:
  75. writer.writeBoolean(_content.asBoolean);
  76. break;
  77. default: // >= JSON_DOUBLE_0_DECIMALS
  78. writer.writeDouble(_content.asDouble, _type - JSON_DOUBLE_0_DECIMALS);
  79. break;
  80. }
  81. }