Qt: How to parse number in a json Qt: How to parse number in a json json json

Qt: How to parse number in a json


You might want to try this instead:

product->product_id = object.value(QString("id")).toVariant().toLongLong();

QVariant unfortunately cannot convert toLong() as it can be seen from its documentation.


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:

  1. get the 32 bit integer value using toInt()
  2. get the double value using toDouble() and cast to long long (that's what's happening behind the scenes when you do toVariant().toLongLong())