diff options
author | Tor Arne Vestbø <tor.arne.vestbo@qt.io> | 2017-04-27 14:43:29 +0200 |
---|---|---|
committer | Tor Arne Vestbø <tor.arne.vestbo@qt.io> | 2017-06-08 11:23:46 +0000 |
commit | a7823b487808a869d4bdc3ff20fddb04967211e1 (patch) | |
tree | b717016a90f67a7d8967601d8245f9e3e7bd87c3 /src | |
parent | 2db0531a57cf85cf1637c26ff4813f5e8e102902 (diff) |
json: Add operator[] to QJsonValue for implicit object and array access
Saves a lot of manual toArray() and toObject() calls when the
JSON structure is usually known anyways. Read only access for now.
Change-Id: I5fd787144198e0443e4da285a11ce2597b66f99f
Reviewed-by: Lars Knoll <lars.knoll@qt.io>
Diffstat (limited to 'src')
-rw-r--r-- | src/corelib/json/qjsonvalue.cpp | 52 | ||||
-rw-r--r-- | src/corelib/json/qjsonvalue.h | 4 |
2 files changed, 56 insertions, 0 deletions
diff --git a/src/corelib/json/qjsonvalue.cpp b/src/corelib/json/qjsonvalue.cpp index 16f4913e9c..33707b6ec3 100644 --- a/src/corelib/json/qjsonvalue.cpp +++ b/src/corelib/json/qjsonvalue.cpp @@ -643,6 +643,58 @@ QJsonObject QJsonValue::toObject() const } /*! + Returns a QJsonValue representing the value for the key \a key. + + Equivalent to calling toObject().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 QJsonValue::operator[](const QString &key) const +{ + if (!isObject()) + return QJsonValue(QJsonValue::Undefined); + + return toObject().value(key); +} + +/*! + \overload + \since 5.10 +*/ +const QJsonValue QJsonValue::operator[](QLatin1String key) const +{ + if (!isObject()) + return QJsonValue(QJsonValue::Undefined); + + return toObject().value(key); +} + +/*! + Returns a QJsonValue representing the value for index \a i. + + Equivalent to calling toArray().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 QJsonValue::operator[](int i) const +{ + if (!isArray()) + return QJsonValue(QJsonValue::Undefined); + + return toArray().at(i); +} + +/*! Returns \c true if the value is equal to \a other. */ bool QJsonValue::operator==(const QJsonValue &other) const diff --git a/src/corelib/json/qjsonvalue.h b/src/corelib/json/qjsonvalue.h index 96ccd34b6e..5d5ec72605 100644 --- a/src/corelib/json/qjsonvalue.h +++ b/src/corelib/json/qjsonvalue.h @@ -137,6 +137,10 @@ public: QJsonObject toObject() const; QJsonObject toObject(const QJsonObject &defaultValue) const; + const QJsonValue operator[](const QString &key) const; + const QJsonValue operator[](QLatin1String key) const; + const QJsonValue operator[](int i) const; + bool operator==(const QJsonValue &other) const; bool operator!=(const QJsonValue &other) const; |