summaryrefslogtreecommitdiffhomepage
path: root/serialize/json-helper.hpp
blob: ebac9ebac2537d18292261a2ac14a58905b51814 (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
43
44
45
46
47
#pragma once
#include <tuple>
#include <fstream>
#include <exception>
#include <filesystem>
#include <nlohmann/json.hpp>

namespace floormat {

struct json_helper final {
    template<typename t>
    [[nodiscard]]
    static t from_json(const std::filesystem::path& pathname);

    template<typename t>
    static void to_json(const t& self, const std::filesystem::path& pathname);
};

template<typename t>
t json_helper::from_json(const std::filesystem::path& pathname)
{
    using Corrade::Utility::Error;
    std::ifstream s;
    s.exceptions(s.exceptions() | std::ios::failbit | std::ios::badbit);
    s.open(pathname, std::ios_base::in);
    t ret;
    nlohmann::json j;
    s >> j;
    ret = j;
    return ret;
}

template<typename t>
void json_helper::to_json(const t& self, const std::filesystem::path& pathname)
{
    using Corrade::Utility::Error;
    nlohmann::json j = self;

    std::ofstream s;
    s.exceptions(s.exceptions() | std::ios::failbit | std::ios::badbit);
    s.open(pathname, std::ios_base::out | std::ios_base::trunc);
    s << j.dump(4);
    s << '\n';
    s.flush();
}

} // namespace floormat