5a3ac484db
JSON, unlike, say, QDataStream, allows building up objects independent of some central object, and combining them into a QJsonDocument later. This suggests returning QJsonObjects from a toJson() const method instead of having the caller supply a QJsonObject. Doing it this way enables transparent move semantics to kick in, too. For deserialization, use a fromJson() named constructor for value-like classes (where identity doesn't matter, only equality). Keep using read(), too, and add a note to explain when to use which form. Also, avoid the triple lookup from if (json.contains("key") && json["key"].isSoughtType()) mFoo = json["key"].toSoughtType(); by using C++17 if-with-initializer and showing the trick with Undefined never being of isSoughtType(): if (const QJsonValue v = json["key"]; v.isSoughtType()) mFoo = v.toSoughtType(); Adjust the discussion to match the new code, up the copyright years and rename some qdoc snippet markers from nondescript [0]/[1] to [toJson]/[fromJson]. Task-number: QTBUG-108857 Pick-to: 6.5 6.4 6.2 Change-Id: Icaa14acc7464fef00a59534679d710252e921383 Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org> Reviewed-by: Mårten Nordheim <marten.nordheim@qt.io>
35 lines
630 B
C++
35 lines
630 B
C++
// Copyright (C) 2016 The Qt Company Ltd.
|
|
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
|
|
|
|
#ifndef LEVEL_H
|
|
#define LEVEL_H
|
|
|
|
#include "character.h"
|
|
|
|
#include <QJsonObject>
|
|
#include <QList>
|
|
|
|
//! [0]
|
|
class Level
|
|
{
|
|
public:
|
|
Level() = default;
|
|
explicit Level(const QString &name);
|
|
|
|
QString name() const;
|
|
|
|
QList<Character> npcs() const;
|
|
void setNpcs(const QList<Character> &npcs);
|
|
|
|
static Level fromJson(const QJsonObject &json);
|
|
QJsonObject toJson() const;
|
|
|
|
void print(int indentation = 0) const;
|
|
private:
|
|
QString mName;
|
|
QList<Character> mNpcs;
|
|
};
|
|
//! [0]
|
|
|
|
#endif // LEVEL_H
|