summaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
authorTor Arne Vestbø <tor.arne.vestbo@qt.io>2017-04-27 14:57:06 +0200
committerTor Arne Vestbø <tor.arne.vestbo@qt.io>2017-06-08 11:23:55 +0000
commitc3a115b90d38d3faac7edcb4ab29f4406a4e382a (patch)
treeaa4164d108c3ef9c43a34c1b42358939b2825fa7 /tests
parenta7823b487808a869d4bdc3ff20fddb04967211e1 (diff)
json: Add operator[] to QJsonDocument for implicit object and array access
Makes it easier to pull out data from a document when the structure is known up front, while still supporting default values if the structure does not match the expectation, eg: int age = QJsonDocument::fromJson(ba)["users"][0]["age"].toInt(-1); Change-Id: Ief0899bbb81610f6f22a56e2ac846121bffe77a0 Reviewed-by: Lars Knoll <lars.knoll@qt.io>
Diffstat (limited to 'tests')
-rw-r--r--tests/auto/corelib/json/tst_qtjson.cpp20
1 files changed, 20 insertions, 0 deletions
diff --git a/tests/auto/corelib/json/tst_qtjson.cpp b/tests/auto/corelib/json/tst_qtjson.cpp
index 32f68c4292..417b9a4173 100644
--- a/tests/auto/corelib/json/tst_qtjson.cpp
+++ b/tests/auto/corelib/json/tst_qtjson.cpp
@@ -146,6 +146,7 @@ private Q_SLOTS:
void parseErrorOffset();
void implicitValueType();
+ void implicitDocumentType();
private:
QString testDataDir;
@@ -2938,5 +2939,24 @@ void tst_QtJson::implicitValueType()
QCOMPARE(objectAsValue["array"][1].toInt(), 666);
}
+void tst_QtJson::implicitDocumentType()
+{
+ QJsonDocument emptyDocument;
+ QCOMPARE(emptyDocument["asObject"], QJsonValue(QJsonValue::Undefined));
+ QCOMPARE(emptyDocument[123], QJsonValue(QJsonValue::Undefined));
+
+ QJsonDocument objectDocument(QJsonObject{{"value", 42}});
+ QCOMPARE(objectDocument["value"].toInt(), 42);
+ QCOMPARE(objectDocument["missingValue"], QJsonValue(QJsonValue::Undefined));
+ QCOMPARE(objectDocument[123], QJsonValue(QJsonValue::Undefined));
+ QCOMPARE(objectDocument["missingValue"].toInt(123), 123);
+
+ QJsonDocument arrayDocument(QJsonArray{665, 666, 667});
+ QCOMPARE(arrayDocument[1].toInt(), 666);
+ QCOMPARE(arrayDocument[-1], QJsonValue(QJsonValue::Undefined));
+ QCOMPARE(arrayDocument["asObject"], QJsonValue(QJsonValue::Undefined));
+ QCOMPARE(arrayDocument[-1].toInt(123), 123);
+}
+
QTEST_MAIN(tst_QtJson)
#include "tst_qtjson.moc"