diff options
Diffstat (limited to 'logic/MMCJson.cpp')
-rw-r--r-- | logic/MMCJson.cpp | 65 |
1 files changed, 62 insertions, 3 deletions
diff --git a/logic/MMCJson.cpp b/logic/MMCJson.cpp index 8de88b6b..23af4fff 100644 --- a/logic/MMCJson.cpp +++ b/logic/MMCJson.cpp @@ -1,13 +1,26 @@ #include "MMCJson.h" + #include <QString> +#include <QUrl> #include <QStringList> #include <math.h> +QJsonDocument MMCJson::parseDocument(const QByteArray &data, const QString &what) +{ + QJsonParseError error; + QJsonDocument doc = QJsonDocument::fromJson(data, &error); + if (error.error != QJsonParseError::NoError) + { + throw JSONValidationError(what + " is not valid JSON: " + error.errorString() + " at " + error.offset); + } + return doc; +} + bool MMCJson::ensureBoolean(const QJsonValue val, const QString what) { if (!val.isBool()) throw JSONValidationError(what + " is not boolean"); - return val.isBool(); + return val.toBool(); } QJsonValue MMCJson::ensureExists(QJsonValue val, const QString what) @@ -24,6 +37,15 @@ QJsonArray MMCJson::ensureArray(const QJsonValue val, const QString what) return val.toArray(); } +QJsonArray MMCJson::ensureArray(const QJsonDocument &val, const QString &what) +{ + if (!val.isArray()) + { + throw JSONValidationError(what + " is not an array"); + } + return val.array(); +} + double MMCJson::ensureDouble(const QJsonValue val, const QString what) { if (!val.isDouble()) @@ -60,9 +82,36 @@ QString MMCJson::ensureString(const QJsonValue val, const QString what) return val.toString(); } +QUrl MMCJson::ensureUrl(const QJsonValue &val, const QString &what) +{ + const QUrl url = QUrl(ensureString(val, what)); + if (!url.isValid()) + { + throw JSONValidationError(what + " is not an url"); + } + return url; +} + +QJsonDocument MMCJson::parseFile(const QString &filename, const QString &what) +{ + QFile f(filename); + if (!f.open(QFile::ReadOnly)) + { + throw FileOpenError(f); + } + return parseDocument(f.readAll(), what); +} + +int MMCJson::ensureInteger(const QJsonValue val, QString what, const int def) +{ + if (val.isUndefined()) + return def; + return ensureInteger(val, what); +} + void MMCJson::writeString(QJsonObject &to, QString key, QString value) { - if(value.size()) + if (!value.isEmpty()) { to.insert(key, value); } @@ -70,7 +119,7 @@ void MMCJson::writeString(QJsonObject &to, QString key, QString value) void MMCJson::writeStringList(QJsonObject &to, QString key, QStringList values) { - if(values.size()) + if (!values.isEmpty()) { QJsonArray array; for(auto value: values) @@ -81,3 +130,13 @@ void MMCJson::writeStringList(QJsonObject &to, QString key, QStringList values) } } +QStringList MMCJson::ensureStringList(const QJsonValue val, QString what) +{ + const QJsonArray array = ensureArray(val, what); + QStringList out; + for (const auto value : array) + { + out.append(ensureString(value)); + } + return out; +} |