From c3a115b90d38d3faac7edcb4ab29f4406a4e382a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Thu, 27 Apr 2017 14:57:06 +0200 Subject: 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 --- src/corelib/json/qjsondocument.cpp | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'src/corelib/json/qjsondocument.cpp') diff --git a/src/corelib/json/qjsondocument.cpp b/src/corelib/json/qjsondocument.cpp index d1169d90e3..6469412054 100644 --- a/src/corelib/json/qjsondocument.cpp +++ b/src/corelib/json/qjsondocument.cpp @@ -550,6 +550,58 @@ void QJsonDocument::setArray(const QJsonArray &array) d->ref.ref(); } +/*! + Returns a QJsonValue representing the value for the key \a key. + + Equivalent to calling object().value(key). + + The returned QJsonValue is QJsonValue::Undefined if the key does not exist, + or if isObject() is false. + + \since 5.10 + + \sa QJsonValue, QJsonValue::isUndefined(), QJsonObject + */ +const QJsonValue QJsonDocument::operator[](const QString &key) const +{ + if (!isObject()) + return QJsonValue(QJsonValue::Undefined); + + return object().value(key); +} + +/*! + \overload + \since 5.10 +*/ +const QJsonValue QJsonDocument::operator[](QLatin1String key) const +{ + if (!isObject()) + return QJsonValue(QJsonValue::Undefined); + + return object().value(key); +} + +/*! + Returns a QJsonValue representing the value for index \a i. + + Equivalent to calling array().at(i). + + The returned QJsonValue is QJsonValue::Undefined, if \a i is out of bounds, + or if isArray() is false. + + \since 5.10 + + \sa QJsonValue, QJsonValue::isUndefined(), QJsonArray + */ +const QJsonValue QJsonDocument::operator[](int i) const +{ + if (!isArray()) + return QJsonValue(QJsonValue::Undefined); + + return array().at(i); +} + /*! Returns \c true if the \a other document is equal to this document. */ -- cgit v1.2.3