Qt: How to parse number in a json
First, QJsonObject::value
returns a QJsonValue
, not a QVariant
. In contrast to QVariant
, QJsonValue
doesn't convert the value when you use a toSomeType()
function but returns a default value when you request a type different then the one being held by the QJsonValue
.
Secondly, JSON doesn't support long integers (64 bit). In fact, it only supports integers as "a special case" of doubles. In the JavaScript world, integral and floating point numbers are basically the same (interpreters might optimize for integers) and are simply called "numbers".
Qt decided to support 32 bit integers as a special case of numbers. They can be accessed when the value holds a double which is a whole number (according to the documentation of QJsonValue::toInt()
). Technically, a double can hold whole numbers with up to 54 bits.
So you have two options:
- get the 32 bit integer value using
toInt()
- get the double value using
toDouble()
and cast tolong long
(that's what's happening behind the scenes when you dotoVariant().toLongLong()
)