-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.cpp
84 lines (65 loc) · 2.18 KB
/
json.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "json.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <fmt/format.h>
namespace El {
// -----------------------------------------------------------------------------
auto Json::from_json(QByteArray const &json, QString const ®ion) -> Json
{
Json me{};
me.parse(region, json);
return me;
}
// -----------------------------------------------------------------------------
Json::Json() = default;
void Json::parse(QString const ®ion, QByteArray const &json)
{
using namespace Qt::Literals::StringLiterals;
// get the JSON object
auto const doc = QJsonDocument::fromJson(json);
if (!doc.isObject()) {
throw Exception{"Invalid JSON document"};
}
auto const obj = doc.object();
// check for success
auto const success = obj.value(u"success"_s);
if (!success.isBool()) {
throw Exception{"Invalid or missing 'success' element"};
}
if (!success.toBool(false)) {
throw Exception{"The JSON document is not good ('success' element is false)"};
}
// get data
auto const data = obj.value(u"data"_s);
if (!data.isObject()) {
throw Exception{"Invalid or missing 'data' element"};
}
// get prices for the region
auto const reg = data.toObject().value(region);
if (!reg.isArray()) {
throw Exception{fmt::format("Invalid or missing region '{}' element", region)};
}
auto const prices = reg.toArray();
// parse price records and store them in price blocks
PriceBlock block{};
for (auto const &el : prices) {
if (!el.isObject()) {
throw Exception{fmt::format("Invalid price element '{}'", el.toString())};
}
auto const o = el.toObject();
auto price = Price::from_json(o);
// check for holes
if (!block.empty() && (block.start_time_h + block.size() != price.time_h)) {
// move the block to the price blocks array
_prices.append(std::move(block));
// block is now empty
}
block.append(price);
}
// append the last block if any
if (!block.empty()) {
_prices.append(std::move(block));
}
}
} // namespace El