aboutsummaryrefslogtreecommitdiff
path: root/src/jsonable.h
blob: 0385fb12f6074698c351858071c2d3ced6c1a199 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#pragma once
#include "json.hpp"
#include "utils.h"
#include <memory>
#include <vector>

class Jsonable {
    public:
        virtual nlohmann::json toJson(void) const = 0;
        operator nlohmann::json() const {return toJson();}
        virtual ~Jsonable() {}
};

template<typename T> std::vector<T> json2vec(const nlohmann::json& data) {
    using std::begin; using std::end;
    return std::vector<T>(begin(data), end(data));
}

template<typename T> std::vector<std::shared_ptr<T>> jsonList2ptrvec(const std::string& type, const std::vector<std::string>& names) {
    std::vector<std::shared_ptr<T>> ret;
    for(auto name : names) {
        auto j = utils::loadJson(type, name);
        ret.push_back(std::shared_ptr<T>(new T(j, j)));
    }
    return ret;
}

template<typename T> std::vector<std::shared_ptr<T>> json2ptrvec(const nlohmann::json& data) {
    std::vector<std::shared_ptr<T>> ret;
    for(nlohmann::json d : data) {
        ret.push_back(T::create(d));
    }
    return ret;
}

template<typename T> std::vector<nlohmann::json> ptrvec2json(std::vector<T> src) {
    std::vector<nlohmann::json> ret;
    for(T i : src) {
        ret.push_back(i->toJson());
    }
    return ret;
}