summaryrefslogtreecommitdiffstats
path: root/examples/corelib/json/savegame/level.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'examples/corelib/json/savegame/level.cpp')
-rw-r--r--examples/corelib/json/savegame/level.cpp44
1 files changed, 34 insertions, 10 deletions
diff --git a/examples/corelib/json/savegame/level.cpp b/examples/corelib/json/savegame/level.cpp
index 5b9fb5c90a..8eda107f46 100644
--- a/examples/corelib/json/savegame/level.cpp
+++ b/examples/corelib/json/savegame/level.cpp
@@ -51,16 +51,23 @@
#include "level.h"
#include <QJsonArray>
+#include <QTextStream>
-Level::Level() {
+Level::Level(const QString &name) : mName(name)
+{
}
-const QList<Character> &Level::npcs() const
+QString Level::name() const
+{
+ return mName;
+}
+
+QVector<Character> Level::npcs() const
{
return mNpcs;
}
-void Level::setNpcs(const QList<Character> &npcs)
+void Level::setNpcs(const QVector<Character> &npcs)
{
mNpcs = npcs;
}
@@ -68,13 +75,19 @@ void Level::setNpcs(const QList<Character> &npcs)
//! [0]
void Level::read(const QJsonObject &json)
{
- mNpcs.clear();
- QJsonArray npcArray = json["npcs"].toArray();
- for (int npcIndex = 0; npcIndex < npcArray.size(); ++npcIndex) {
- QJsonObject npcObject = npcArray[npcIndex].toObject();
- Character npc;
- npc.read(npcObject);
- mNpcs.append(npc);
+ if (json.contains("name") && json["name"].isString())
+ mName = json["name"].toString();
+
+ if (json.contains("npcs") && json["npcs"].isArray()) {
+ QJsonArray npcArray = json["npcs"].toArray();
+ mNpcs.clear();
+ mNpcs.reserve(npcArray.size());
+ for (int npcIndex = 0; npcIndex < npcArray.size(); ++npcIndex) {
+ QJsonObject npcObject = npcArray[npcIndex].toObject();
+ Character npc;
+ npc.read(npcObject);
+ mNpcs.append(npc);
+ }
}
}
//! [0]
@@ -82,6 +95,7 @@ void Level::read(const QJsonObject &json)
//! [1]
void Level::write(QJsonObject &json) const
{
+ json["name"] = mName;
QJsonArray npcArray;
foreach (const Character npc, mNpcs) {
QJsonObject npcObject;
@@ -91,3 +105,13 @@ void Level::write(QJsonObject &json) const
json["npcs"] = npcArray;
}
//! [1]
+
+void Level::print(int indentation) const
+{
+ const QString indent(indentation * 2, ' ');
+ QTextStream(stdout) << indent << "Name:\t" << mName << "\n";
+
+ QTextStream(stdout) << indent << "NPCs:\n";
+ for (const Character &character : mNpcs)
+ character.print(2);
+}