Krzysztof Grobelny | dcc4e19 | 2021-03-08 09:09:34 +0000 | [diff] [blame^] | 1 | #pragma once |
| 2 | |
| 3 | #include <nlohmann/json.hpp> |
| 4 | |
| 5 | #include <string_view> |
| 6 | |
| 7 | namespace utils |
| 8 | { |
| 9 | |
| 10 | template <class T> |
| 11 | struct is_vector : std::false_type |
| 12 | {}; |
| 13 | |
| 14 | template <class T> |
| 15 | struct is_vector<std::vector<T>> : std::true_type |
| 16 | {}; |
| 17 | |
| 18 | template <class T> |
| 19 | constexpr bool is_vector_v = is_vector<T>::value; |
| 20 | |
| 21 | template <class T> |
| 22 | std::optional<T> readJson(const nlohmann::json& json) |
| 23 | { |
| 24 | if constexpr (is_vector_v<T>) |
| 25 | { |
| 26 | if (json.is_array()) |
| 27 | { |
| 28 | auto result = T{}; |
| 29 | for (const auto& item : json.items()) |
| 30 | { |
| 31 | if (auto val = readJson<typename T::value_type>(item.value())) |
| 32 | { |
| 33 | result.emplace_back(*val); |
| 34 | } |
| 35 | } |
| 36 | return result; |
| 37 | } |
| 38 | } |
| 39 | else |
| 40 | { |
| 41 | if (const T* val = json.get_ptr<const T*>()) |
| 42 | { |
| 43 | return *val; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | return std::nullopt; |
| 48 | } |
| 49 | |
| 50 | template <class T> |
| 51 | std::optional<T> readJson(const nlohmann::json& json, std::string_view key) |
| 52 | { |
| 53 | auto it = json.find(key); |
| 54 | if (it != json.end()) |
| 55 | { |
| 56 | const nlohmann::json& subJson = *it; |
| 57 | return readJson<T>(subJson); |
| 58 | } |
| 59 | |
| 60 | return std::nullopt; |
| 61 | } |
| 62 | |
| 63 | } // namespace utils |