Converting QJsonObject to QVariantMap gives empty map

  • 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;
        if(! | QIODevice::Text))
            qWarning() << Q_FUNC_INFO << "Failed to open file";
            QJsonDocument jsonDoc;
            QString jsonText = jsonFile.readAll();
            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();
                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?

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

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.