Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Converting QJsonObject to QVariantMap gives empty map

Converting QJsonObject to QVariantMap gives empty map

Scheduled Pinned Locked Moved Solved General and Desktop
json parserqvariantmapempty
2 Posts 1 Posters 5.2k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    diredko
    wrote on 5 Aug 2017, 09:04 last edited by
    #1

    Hi All,

    I'm trying to read some JSON file and convert it into QVariantMap. For this I use QJsonDocument.
    The file is read fine and JSON parsing doesn't give any error but for some reason when I convert this into QVariantMap it is empty.

    Please take a look at the code below:

        QString fileNameTemplate("/tmp/%1.json");
        QString fileName = fileNameTemplate.arg("file");
    
        qDebug() << Q_FUNC_INFO << "Reading from file: " << fileName;
    
        QFile jsonFile;
        jsonFile.setFileName(fileName);
    
        if(!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            qWarning() << Q_FUNC_INFO << "Failed to open file";
        }
        else
        {
            QJsonDocument jsonDoc;
            QString jsonText = jsonFile.readAll();
            jsonFile.close();
            qDebug() << Q_FUNC_INFO << "File contents" << jsonText;
            QJsonParseError error;
            jsonDoc.fromJson(jsonText.toLocal8Bit(), &error);
    
            if(error.error == QJsonParseError::NoError)
            {
                 //This QVariant is empty
                QVariant variant = jsonDoc.object().toVariantMap();
    
                fillInMap(variant.toMap());
            }
            else
            {
                qWarning() << Q_FUNC_INFO << "JSON Parse Error: " << error.errorString();
            }
        }
    

    The output is as follows:

    ... Reading from file:  "/tmp/file.json"
    ... File contents "{\n\"variant\":\"variant\"\n}\n"
    ... fillInMap(const QVariantMap &) QMap()
    

    Does anybody have an idea of what I'm doing wrong here?

    1 Reply Last reply
    1
    • D Offline
      D Offline
      diredko
      wrote on 5 Aug 2017, 09:46 last edited by
      #2

      I found the reason for having this issue. I didn't store the result of fromJson function

      1 Reply Last reply
      0

      2/2

      5 Aug 2017, 09:46

      • Login

      • Login or register to search.
      2 out of 2
      • First post
        2/2
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved