-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonhelper.cpp
65 lines (52 loc) · 1.66 KB
/
jsonhelper.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
#include "jsonhelper.h"
#include <QtQml>
void JsonHelper::declareQML()
{
qmlRegisterSingletonType<JsonHelper>("TOP.Utils", 1, 0, "JsonHelper", qmlJsonHelperSingleton);
}
void JsonHelper::modifyValue(QJsonObject &obj, const QString &path, const QJsonValue &newValue)
{
const int indexOfDot = path.indexOf('.');
const QString propertyName = path.left(indexOfDot);
const QString subPath = indexOfDot>0 ? path.mid(indexOfDot+1) : QString();
QJsonValue subValue = obj[propertyName];
if(subPath.isEmpty()) {
subValue = newValue;
}
else {
QJsonObject obj = subValue.toObject();
modifyValue(obj,subPath,newValue);
subValue = obj;
}
obj[propertyName] = subValue;
}
void JsonHelper::modifyValue(QJsonDocument &doc, const QString &path, const QJsonValue &newValue)
{
QJsonObject obj = doc.object();
modifyValue(obj,path,newValue);
doc = QJsonDocument(obj);
}
void JsonHelper::removeKey(QJsonObject &obj, const QString &path, const QString &key)
{
const int indexOfDot = path.indexOf('.');
const QString propertyName = path.left(indexOfDot);
const QString subPath = indexOfDot>0 ? path.mid(indexOfDot+1) : QString();
QJsonObject subObject = obj[propertyName].toObject();
if(subPath.isEmpty()) {
subObject.remove(key);
}
else {
removeKey(subObject,subPath,key);
}
obj[propertyName] = subObject;
}
void JsonHelper::removeKey(QJsonDocument &doc, const QString &path, const QString &key)
{
QJsonObject obj = doc.object();
removeKey(obj,path,key);
doc = QJsonDocument(obj);
}
QString JsonHelper::docToString(QJsonDocument doc)
{
return doc.toJson();
}