From ae981f224de9d2a24bfb1547e2049b6ccd9fc4ac Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Thu, 30 Oct 2014 10:59:11 +0100 Subject: Add conversion between QVariantHash and QJsonObject Adds automatic conversion from QVariants with a QVariantHash to QJsonValue and explicit methods for conversion between QVariantHash and QJsonObject. [ChangeLog][QtCore][QJsonObject] Added conversion to and from QVariantHash Change-Id: I140ef881463acabaab2648e28209487d8ad18e0d Reviewed-by: Lars Knoll --- src/corelib/json/qjsonobject.cpp | 43 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) (limited to 'src/corelib/json/qjsonobject.cpp') diff --git a/src/corelib/json/qjsonobject.cpp b/src/corelib/json/qjsonobject.cpp index bc74092f597..df604e4433c 100644 --- a/src/corelib/json/qjsonobject.cpp +++ b/src/corelib/json/qjsonobject.cpp @@ -192,7 +192,7 @@ QJsonObject &QJsonObject::operator =(const QJsonObject &other) The keys in \a map will be used as the keys in the JSON object, and the QVariant values will be converted to JSON values. - \sa toVariantMap(), QJsonValue::fromVariant() + \sa fromVariantHash(), toVariantMap(), QJsonValue::fromVariant() */ QJsonObject QJsonObject::fromVariantMap(const QVariantMap &map) { @@ -208,6 +208,8 @@ QJsonObject QJsonObject::fromVariantMap(const QVariantMap &map) Converts this object to a QVariantMap. Returns the created map. + + \sa toVariantHash() */ QVariantMap QJsonObject::toVariantMap() const { @@ -221,6 +223,45 @@ QVariantMap QJsonObject::toVariantMap() const return map; } +/*! + Converts the variant hash \a hash to a QJsonObject. + \since 5.5 + + The keys in \a hash will be used as the keys in the JSON object, + and the QVariant values will be converted to JSON values. + + \sa fromVariantMap(), toVariantHash(), QJsonValue::fromVariant() + */ +QJsonObject QJsonObject::fromVariantHash(const QVariantHash &hash) +{ + // ### this is implemented the trivial way, not the most efficient way + + QJsonObject object; + for (QVariantHash::const_iterator it = hash.constBegin(); it != hash.constEnd(); ++it) + object.insert(it.key(), QJsonValue::fromVariant(it.value())); + return object; +} + +/*! + Converts this object to a QVariantHash. + \since 5.5 + + Returns the created hash. + + \sa toVariantMap() + */ +QVariantHash QJsonObject::toVariantHash() const +{ + QVariantHash hash; + if (o) { + for (uint i = 0; i < o->length; ++i) { + QJsonPrivate::Entry *e = o->entryAt(i); + hash.insert(e->key(), QJsonValue(d, o, e->value).toVariant()); + } + } + return hash; +} + /*! Returns a list of all keys in this object. */ -- cgit v1.2.3