blob: 2ae606fac032c73cb49805c7bd7cfd3493961ddf [file] [log] [blame]
Krzysztof Grobelnydcc4e192021-03-08 09:09:34 +00001#pragma once
2
3#include <nlohmann/json.hpp>
4
5#include <string_view>
6
7namespace utils
8{
9
10template <class T>
11struct is_vector : std::false_type
12{};
13
14template <class T>
15struct is_vector<std::vector<T>> : std::true_type
16{};
17
18template <class T>
19constexpr bool is_vector_v = is_vector<T>::value;
20
21template <class T>
22std::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
50template <class T>
51std::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