59 lines
1.8 KiB
C++
59 lines
1.8 KiB
C++
#include "jsonparser.h"
|
|
|
|
#include <QJsonArray>
|
|
#include <QJsonObject>
|
|
|
|
#include "../model/tablemodel.h"
|
|
|
|
QList<QHash<int, QVariant>> JsonParser::toItemValuesList(const QByteArray& jsonData,
|
|
const QString& objectName) {
|
|
QList<QHash<int, QVariant>> result;
|
|
|
|
if (jsonData.isEmpty()) {
|
|
return result;
|
|
}
|
|
|
|
QJsonArray itemArray = extractItemArray(jsonData, objectName);
|
|
|
|
foreach (QJsonValue value, itemArray) {
|
|
QJsonObject itemJsonObject = value.toObject();
|
|
QHash<int, QVariant> values = jsonObjectToItemValues(itemJsonObject);
|
|
result.append(values);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
QHash<int, QVariant> JsonParser::jsonObjectToItemValues(const QJsonObject& itemJsonObject) {
|
|
QHash<int, QVariant> values;
|
|
|
|
// TODO make this more generic (by reading from model meta data)
|
|
values[TableModel::NameRole] =
|
|
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::NameRole)].toString();
|
|
values[TableModel::DescriptionRole] =
|
|
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::DescriptionRole)].toString();
|
|
values[TableModel::InfoRole] =
|
|
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::InfoRole)].toString();
|
|
values[TableModel::AmountRole] =
|
|
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::AmountRole)].toInt();
|
|
values[TableModel::FactorRole] =
|
|
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::FactorRole)].toDouble();
|
|
|
|
return values;
|
|
}
|
|
|
|
JsonParser::JsonParser() {}
|
|
|
|
QJsonArray JsonParser::extractItemArray(const QByteArray& jsonData, const QString& objectName) {
|
|
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
|
|
QJsonArray itemArray;
|
|
if (objectName.isEmpty()) {
|
|
itemArray = doc.array();
|
|
|
|
} else {
|
|
QJsonObject rootObject = doc.object();
|
|
itemArray = rootObject.value(objectName).toArray();
|
|
}
|
|
|
|
return itemArray;
|
|
}
|