JsonHelpers.h 994 B

123456789101112131415161718192021222324252627282930313233343536
  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 std::vector<T> jsonArrToVector(JsonArray& arr, std::function<T (const String&)> converter, const bool unique = true) {
  11. std::vector<T> vec;
  12. for (size_t i = 0; i < arr.size(); ++i) {
  13. String strVal = arr.get<const char*>(i);
  14. T convertedVal = converter(strVal);
  15. // inefficient, but everything using this is tiny, so doesn't matter
  16. if (!unique || std::find(vec.begin(), vec.end(), convertedVal) == vec.end()) {
  17. vec.push_back(convertedVal);
  18. }
  19. }
  20. return vec;
  21. }
  22. template<typename T>
  23. static void vectorToJsonArr(JsonArray& arr, const std::vector<T>& vec, std::function<String (const T&)> converter) {
  24. for (typename std::vector<T>::const_iterator it = vec.begin(); it != vec.end(); ++it) {
  25. arr.add(converter(*it));
  26. }
  27. }
  28. };
  29. #endif