-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplateSaving.cpp
68 lines (55 loc) · 1.75 KB
/
templateSaving.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <crow.h>
#include <fstream>
#include "templateSaving.h"
using namespace std;
using namespace crow;
template <typename T>
void saveToFile(map<string, T> data, string filename)
{
// Open the file for writing
ofstream file(filename);
if (file.is_open())
{
// Create a new JSON write value use to write to the file.
json::wvalue jsonWriteValue;
// For each object in the map, convert the object to JSON and add to the write value.
int index = 0;
for (pair<string, T> keyValuePair : data)
{
// first: gives you access to the first item in the pair.
// second: gives you access to the second item in the pair.
jsonWriteValue[index] = keyValuePair.second.convertToJson();
index++;
}
// Write the JSON to the file.
file << jsonWriteValue.dump();
file.close();
}
}
template <typename T>
map<string, T> loadFromFile(string filename)
{
map<string, T> data;
// Open the file for reading.
ifstream file(filename);
// If the file is open.
if (file.is_open())
{
// Create a stream for reading in the file.
ostringstream stringStreamJson;
// Read the entire JSON string.
stringStreamJson << file.rdbuf();
// Load the string into a JSON read value object.
json::rvalue jsonReadValue = json::load(stringStreamJson.str());
// Close the file.
file.close();
// For each item in the JSON convert it to an object,
// and add it to the data map.
for (json::rvalue item : jsonReadValue)
{
T object{item};
data[object.getId()] = object;
}
}
return data;
}