JsonHashTable.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Arduino JSON library
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #pragma once
  6. #include "EscapedString.h"
  7. #include "JsonObjectBase.h"
  8. namespace ArduinoJson
  9. {
  10. namespace Generator
  11. {
  12. template<int N>
  13. class JsonHashTable : public JsonObjectBase
  14. {
  15. public:
  16. JsonHashTable()
  17. {
  18. itemCount = 0;
  19. }
  20. template<typename T>
  21. void add(const char* key, T value)
  22. {
  23. if (itemCount >= N) return;
  24. items[itemCount].key.set(key);
  25. items[itemCount].value.set(value);
  26. itemCount++;
  27. }
  28. template<int DIGITS>
  29. void add(const char* key, double value)
  30. {
  31. if (itemCount >= N) return;
  32. items[itemCount].key.set(key);
  33. items[itemCount].value.set<DIGITS>(value);
  34. itemCount++;
  35. }
  36. using JsonObjectBase::printTo;
  37. private:
  38. struct KeyValuePair
  39. {
  40. Internals::EscapedString key;
  41. Internals::JsonValue value;
  42. };
  43. KeyValuePair items[N];
  44. int itemCount;
  45. virtual size_t printTo(Print& p) const
  46. {
  47. size_t n = 0;
  48. n += p.write('{');
  49. for (int i = 0; i < itemCount; i++)
  50. {
  51. if (i > 0)
  52. {
  53. n += p.write(',');
  54. }
  55. n += items[i].key.printTo(p);
  56. n += p.write(':');
  57. n += items[i].value.printTo(p);
  58. }
  59. n += p.write('}');
  60. return n;
  61. }
  62. };
  63. }
  64. }