[Solved] QJsonDocumentt can't read with fromJson()



  • Hi,

    I'm trying to convert some existing JSON parsing code from QJson to Qt 5's JSON classes. The JSON files were parsed correctly with QJson, but can't be loaded into QJsonDocument. I used the following code:

    @
    QFile jsonFIle(":/path/to/json/file");
    jsonFile.open(QIODevice::ReadOnly | QIODevice::Text);
    QJsonDocument doc;
    QJsonParseError parseError;
    doc.fromJson(jsonFile.readAll(), &parseError);
    jsonFile.close();
    if (parseError.error != QJsonParseError::NoError)
    {
    // Report fatal error
    }
    // Analyze the content...
    @

    With the debugger I can see the file gets read, the encoding if certainly UTF-8 (I even tried QString(jsonFile.readAll()).toUtf8() just to make sure), and the content is correct. But I end up getting an empty QJsonDocument (doc.isNull() returns true). QJsonParseError offers no help at all, claiming the parsing ended with QJsonParseError::NoError (!?).

    Am I doing something wrong? The JSON files are certainly decodable (with Qt in UTF-8), and can be parsed correctly (I tested with QJson and Python's json.tool). And I can't understand why QJsonParseError keeps telling me there's no errors...

    Thanks in advance.

    Note: I'm using Qt 5.1 from the official installer (MSVC 2012 64-bit with OpenGL).


  • Lifetime Qt Champion

    Hi,

    You're using QJsonDocument wrong: fromJson is a static function.

    @QJsonDocument doc = QJsonDocument::fromJson(jsonFile.readAll(), &parseError);@

    and you should be good



  • Obviously I got too much ahead of myself...Should have read the documentation more carefully. Thanks.


  • Lifetime Qt Champion

    You're welcome ! Happy coding !


Log in to reply
 

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