Conversion between QJsonObject and QVariantMap

Discuss anything related to product development
Post Reply
regon
Posts: 2
Joined: Wed Apr 03 2024 4:49 pm

Conversion between QJsonObject and QVariantMap

Post 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.
barbara
Posts: 454
Joined: Sat Apr 04 2015 2:32 am
Contact:

Re: Conversion between QJsonObject and QVariantMap

Post by barbara »

Thank you for reporting this issues. We will add this as a unit test and make any changes which are required.
barbara
Posts: 454
Joined: Sat Apr 04 2015 2:32 am
Contact:

Re: Conversion between QJsonObject and QVariantMap

Post 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
Post Reply