Items can be added to model dynamically.
This commit is contained in:
58
formats/jsonparser.cpp
Normal file
58
formats/jsonparser.cpp
Normal file
@ -0,0 +1,58 @@
|
||||
#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(QString("items")).toArray();
|
||||
}
|
||||
|
||||
return itemArray;
|
||||
}
|
||||
Reference in New Issue
Block a user