I am trying to convert QJsonValues into their correct data types, but the conversion always ends up returning their default value.
For example, I have the following JSON object:
{
"val1": 99,
"val2": true,
"val3": "test"
}
I'm getting these values with:
QJsonValue val1 = jsonObj.value("val1");
QJsonValue val2 = jsonObj.value("val2");
QJsonValue val3 = jsonObj.value("val3");
Now, if I check these QJsonValues in the Debug view, they all have their correct value and data types.
I'm seeing...
I now do the following:
int valInt1 = val1.toInt();
bool valBool2 = val2.toBool();
QString valString3 = val3.toString();
This will give me 0 for valInt1 , false for valBool2 and "test" for valString3 . For some reason, toString() seems to be working correctly, but the other conversion methods all result in their default value.
With val1 I can do the following to make it work:
int valInt1 = val1.toString().toInt();
But that is not an option for bool values.
Does anyone know how I could solve this problem? I believe I'm doing everything right here. Not sure what the issue might be and the documentation does things exactly how I would do them, but the conversions always return default values.
I have solved this problem for now by converting the JsonObject to a QVariantMap and ignoring the QJsonValues. They are either bugged or I do not understand how they work.
QVariantMap map = jsonObj.toVariantMap();
int valInt1 = map.value("val1").toInt();
bool valBool2 = map.value("val2").toBool();
QString valString3 = map.value("val3").toString();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.