Qt: how to parse a number into json
This is how my json looks like. As you can see, the key ID
is a number.
{
"id" : 1223324342,
"name" : "test",
"files"...
}
How can I parse a number and put it in a variable with a long data type? Currently this is what I have, but it keeps 0 instead.
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject object = document.object();
product->product_id = object.value(QString("id")).toString().toLong();
QJsonObject::value
Returns first QJsonValue
, not QVariant
. In contrast QVariant
, QJsonValue
does not convert the value when you use the function toSomeType()
, but returns the default value when you ask for a type other than the one that is being held QJsonValue
.
Second, JSON does not support long integers (64 bits). In fact, it only supports integers as a "special case" of doublings. In the JavaScript world, the numbers of integrals and floating point numbers are basically the same (interpreters can optimize for integers) and are simply called "numbers".
Qt chose to support 32-bit integers as a special case of numbers. They can be accessed when the value contains a double, which is an integer (according to the documentationQJsonValue::toInt()
). Technically, a double can hold integers up to 54 bits.
So, you have two options:
- get 32 โโbit integer value with
toInt()
- get double value with
toDouble()
and apply tolong long
(what happens behind the scenes when you dotoVariant().toLongLong()
)
source to share