From 201675f9c433079da6aa93f8a9bd602b53698936 Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Thu, 24 May 2018 21:07:42 +0200 Subject: [PATCH] simplified reading and writing --- source/DataModel.cpp | 34 ++++++---------------------------- source/DataModel.h | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/source/DataModel.cpp b/source/DataModel.cpp index e1362b6..803b541 100644 --- a/source/DataModel.cpp +++ b/source/DataModel.cpp @@ -10,36 +10,14 @@ DataModel::DataModel(QObject *parent) void DataModel::write(QJsonObject &target) const { - QJsonObject metaData; - m_metaData.write(metaData); - target["MetaData"] = metaData; - - QJsonObject verbEnd; - m_verbEnd.write(verbEnd); - target["VerbEnd"] = verbEnd; - - QJsonObject genus; - m_genus.write(genus); - target["Genus"] = genus; + write(m_metaData, target, "MetaData"); + write(m_verbEnd, target, "VerbEnd"); + write(m_genus, target, "Genus"); } void DataModel::read(const QJsonObject &source) { - const auto &metaData = source["MetaData"]; - if (metaData.isObject()) - { - m_metaData.read(metaData.toObject()); - } - - const auto &verbEnd = source["VerbEnd"]; - if (verbEnd.isObject()) - { - m_verbEnd.read(verbEnd.toObject()); - } - - const auto &genus = source["Genus"]; - if (genus.isObject()) - { - m_genus.read(genus.toObject()); - } + read(m_metaData, source, "MetaData"); + read(m_verbEnd, source, "VerbEnd"); + read(m_genus, source, "Genus"); } diff --git a/source/DataModel.h b/source/DataModel.h index db7a475..ec37fb0 100644 --- a/source/DataModel.h +++ b/source/DataModel.h @@ -20,4 +20,25 @@ public: void write(QJsonObject &target) const; void read(const QJsonObject &source); + +private: + template + void write( + const ModelType &model, QJsonObject &target, const char *name) const + { + QJsonObject jsonObject; + model.write(jsonObject); + target[name] = jsonObject; + } + + template + void read( + ModelType &model, const QJsonObject &source, const char *name) const + { + const auto &jsonObject = source[name]; + if (jsonObject.isObject()) + { + model.read(jsonObject.toObject()); + } + } };