JsonHashTable.h 1.2 KB

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