JsonHelpers.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <ArduinoJson.h>
  2. #include <vector>
  3. #include <functional>
  4. #include <algorithm>
  5. #ifndef _JSON_HELPERS_H
  6. #define _JSON_HELPERS_H
  7. class JsonHelpers {
  8. public:
  9. template<typename T>
  10. static void copyFrom(JsonArray arr, std::vector<T> vec) {
  11. for (typename std::vector<T>::const_iterator it = vec.begin(); it != vec.end(); ++it) {
  12. arr.add(*it);
  13. }
  14. }
  15. template<typename T>
  16. static void copyTo(JsonArray arr, std::vector<T> vec) {
  17. for (size_t i = 0; i < arr.size(); ++i) {
  18. JsonVariant val = arr[i];
  19. vec.push_back(val.as<T>());
  20. }
  21. }
  22. template<typename T, typename StrType>
  23. static std::vector<T> jsonArrToVector(JsonArray& arr, std::function<T (const StrType)> converter, const bool unique = true) {
  24. std::vector<T> vec;
  25. for (size_t i = 0; i < arr.size(); ++i) {
  26. StrType strVal = arr[i];
  27. T convertedVal = converter(strVal);
  28. // inefficient, but everything using this is tiny, so doesn't matter
  29. if (!unique || std::find(vec.begin(), vec.end(), convertedVal) == vec.end()) {
  30. vec.push_back(convertedVal);
  31. }
  32. }
  33. return vec;
  34. }
  35. template<typename T, typename StrType>
  36. static void vectorToJsonArr(JsonArray& arr, const std::vector<T>& vec, std::function<StrType (const T&)> converter) {
  37. for (typename std::vector<T>::const_iterator it = vec.begin(); it != vec.end(); ++it) {
  38. arr.add(converter(*it));
  39. }
  40. }
  41. };
  42. #endif