-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathjson_mapper.cpp
53 lines (45 loc) · 1.59 KB
/
json_mapper.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
#include <QJsonDocument>
#include <QJsonObject>
#include <QQmlPropertyMap>
class JsonMapper : public QObject
{
Q_OBJECT
public:
explicit JsonMapper(QObject *parent = nullptr) : QObject(parent) {}
Q_INVOKABLE QQmlPropertyMap* mapJson(const QString& filePath) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "Could not open file for reading:" << filePath;
return nullptr;
}
QByteArray jsonData = file.readAll();
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
if (!jsonDoc.isObject()) {
qWarning() << "JSON data is not an object:" << filePath;
return nullptr;
}
QJsonObject jsonObj = jsonDoc.object();
QQmlPropertyMap* map = new QQmlPropertyMap();
for (auto it = jsonObj.begin(); it != jsonObj.end(); ++it) {
QString key = it.key();
QVariant value = mapJsonValue(it.value());
map->insert(key, value);
}
return map;
}
private:
QVariant mapJsonValue(const QJsonValue& jsonValue) {
if (jsonValue.isObject()) {
QJsonObject jsonObj = jsonValue.toObject();
QQmlPropertyMap* map = new QQmlPropertyMap();
for (auto it = jsonObj.begin(); it != jsonObj.end(); ++it) {
QString key = it.key();
QVariant value = mapJsonValue(it.value());
map->insert(key, value);
}
return QVariant::fromValue(map);
} else {
return jsonValue.toVariant();
}
}
};