Page 1 of 1
Conversion between QJsonObject and QVariantMap
Posted: Wed Apr 10 2024 7:53 am
by regon
Code: Select all
QVariant json_to_variant() {
QJsonObject t_json;
t_json["111"] = 111;
t_json["222"] = 222;
QJsonObject root;
root["root"] = t_json;
auto t_map = root.toVariantMap();
QVariant t_var = t_map;
return t_var;
}
QVariant t_var = json_to_variant();
QJsonObject t_root = t_var.toJsonObject();
QJsonObject t_json = t_root["root"].toObject();
int value1 = t_json["111"].toInt();
int value2 = t_json["222"].toInt();
When I execute this code, the values of value1 and value2 are both 0.
Re: Conversion between QJsonObject and QVariantMap
Posted: Wed Apr 10 2024 3:43 pm
by barbara
Thank you for reporting this issues. We will add this as a unit test and make any changes which are required.
Re: Conversion between QJsonObject and QVariantMap
Posted: Sat Apr 13 2024 7:08 pm
by barbara
We have taken a look at your reported issue and we want to discuss what line 2 is really doing.
Line 2 is taking a QVariantMap and storing it in a QVariant. If you call tmpVariant.typeName() it will return the data type of what the variant is storing. In this example code it is storing a QVariantMap. On line 3 you are calling toJsonObject() which fails because the variant does not contain a QJsonObject.
Code: Select all
// expanded 'auto' from your json_to_variant() function
QVariantMap tmpMap = root.toVariantMap();
// line 2 in question ( see above )
QVariant tmpVariant = tmpMap;
// line 3 ( see above )
QJsonObject tmpRoot = tmpVariant.toJsonObject();
If you really want to keep line 2, here is how you would retrieve the QJsonObject. We are curious why you are saving the QVariantMap to a QVariant.
Code: Select all
QVariantMap tmpMap = root.toVariantMap();
QVariant tmpVariant = tmpMap;
// modified code
QJsonObject tmpRoot = QJsonObject::fromVariantMap(tmpVariant.toMap());
// original code
QJsonObject tmpChild_1 = tmpRoot["root"].toObject();
int value1 = tmpChild_1["111"].toInt();
If you have other questions please let us know.
Barbara