From 507f1889e2b21d0b3367715dc5e63e124433a992 Mon Sep 17 00:00:00 2001 From: Mitch Curtis Date: Thu, 22 Aug 2013 16:25:13 +0200 Subject: Add QJsonValue::toInt(). It's a nice feature to have. MSVC also complains about using doubles to create enum values, so the ugly workaround is: enumValue = MyEnum(qRound(json["myEnumValue"].toDouble())); [ChangeLog][QtCore][QJsonValue]Added QJsonValue::toInt(). Change-Id: I1a200b912abf66b2e96390b1980caff26cfa2685 Reviewed-by: Thiago Macieira Reviewed-by: Lars Knoll --- src/corelib/json/qjsonvalue.cpp | 13 +++++++++++++ src/corelib/json/qjsonvalue.h | 2 ++ 2 files changed, 15 insertions(+) (limited to 'src/corelib') diff --git a/src/corelib/json/qjsonvalue.cpp b/src/corelib/json/qjsonvalue.cpp index 3aba6124b8..ef9f057d77 100644 --- a/src/corelib/json/qjsonvalue.cpp +++ b/src/corelib/json/qjsonvalue.cpp @@ -448,6 +448,19 @@ bool QJsonValue::toBool(bool defaultValue) const return b; } +/*! + Converts the value to an int and returns it. + + If type() is not Double or the value is not a whole number, + the \a defaultValue will be returned. + */ +int QJsonValue::toInt(int defaultValue) const +{ + if (t == Double && int(dbl) == dbl) + return dbl; + return defaultValue; +} + /*! Converts the value to a double and returns it. diff --git a/src/corelib/json/qjsonvalue.h b/src/corelib/json/qjsonvalue.h index c8efab5d5f..b18bbde0f7 100644 --- a/src/corelib/json/qjsonvalue.h +++ b/src/corelib/json/qjsonvalue.h @@ -103,6 +103,7 @@ public: inline bool isUndefined() const { return type() == Undefined; } bool toBool(bool defaultValue = false) const; + int toInt(int defaultValue = 0) const; double toDouble(double defaultValue = 0) const; QString toString(const QString &defaultValue = QString()) const; QJsonArray toArray() const; @@ -158,6 +159,7 @@ public: inline bool isUndefined() const { return type() == QJsonValue::Undefined; } inline bool toBool() const { return toValue().toBool(); } + inline int toInt() const { return toValue().toInt(); } inline double toDouble() const { return toValue().toDouble(); } inline QString toString() const { return toValue().toString(); } QJsonArray toArray() const; -- cgit v1.2.3