json: Add defaultValue to QJsonValueRef toInt/toBool/toDouble/toString

Currently QJsonValue and QJsonValueRef behave differently in
regard to the default values leading to confusion compile errors
depending on which of the two types one is actually using. Before
this change it was possible to write:

QJsonValue value = jsonObject["item"];
QString name = value.toString(QStringLiteral("default"));

but not:

QString name = jsonObject["item"].toString(QStringLiteral("default"));

Change-Id: Id1185acf339aa3a91e97848e85d068f84552df71
Reviewed-by: Lars Knoll <lars.knoll@digia.com>
Reviewed-by: Jędrzej Nowacki <jedrzej.nowacki@digia.com>
This commit is contained in:
Holger Hans Peter Freyther 2014-06-10 10:41:28 +02:00 committed by Jędrzej Nowacki
parent e2a7293290
commit afbc2c75e3
2 changed files with 24 additions and 0 deletions

View File

@ -170,6 +170,12 @@ public:
QJsonArray toArray() const;
QJsonObject toObject() const;
// ### Qt 6: Add default values
inline bool toBool(bool defaultValue) const { return toValue().toBool(defaultValue); }
inline int toInt(int defaultValue) const { return toValue().toInt(defaultValue); }
inline double toDouble(double defaultValue) const { return toValue().toDouble(defaultValue); }
inline QString toString(const QString &defaultValue) const { return toValue().toString(defaultValue); }
inline bool operator==(const QJsonValue &other) const { return toValue() == other; }
inline bool operator!=(const QJsonValue &other) const { return toValue() != other; }

View File

@ -132,6 +132,7 @@ private Q_SLOTS:
void testTrailingComma();
void testDetachBug();
void testJsonValueRefDefault();
void valueEquals();
@ -2425,5 +2426,22 @@ void tst_QtJson::longStrings()
}
}
void tst_QtJson::testJsonValueRefDefault()
{
QJsonObject empty;
QCOMPARE(empty["n/a"].toString(), QString());
QCOMPARE(empty["n/a"].toString("default"), QStringLiteral("default"));
QCOMPARE(empty["n/a"].toBool(), false);
QCOMPARE(empty["n/a"].toBool(true), true);
QCOMPARE(empty["n/a"].toInt(), 0);
QCOMPARE(empty["n/a"].toInt(42), 42);
QCOMPARE(empty["n/a"].toDouble(), 0.0);
QCOMPARE(empty["n/a"].toDouble(42.0), 42.0);
}
QTEST_MAIN(tst_QtJson)
#include "tst_qtjson.moc"