Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt and JSON resource parsing - Empty QJSONDocument

Tags:

c++

json

qt

qjson

I've got a trouble while parsing JSON using QJON objects.

I read a json file of mine referenced in a resource file, read the content and try to initialize a QJSONDocument from the QString I got. And it seems it's not working

Here is the code I use :

QFile myFile(":/mime/iconemapping.json");

myFile.open(QIODevice::ReadOnly);

QJsonDocument jsonContent;
QJsonObject root;
QString jsonString = QString::fromUtf8(myFile.readAll()).simplified();

jsonContent = QJsonDocument::fromJson(jsonString.toUtf8());

root = jsonContent.object();

QJsonObject ext = root["extensions"].toObject();

QStringList listeCle = ext.keys();
int s = listeCle.size();

for (int i = 0; i < listeCle.size(); i++) {
    QString cle = listeCle.at(i).toLocal8Bit().constData();
    MAP_ICONE_MIME.insert(cle, ext[cle].toString());
}

myFile.close();

Before I try QJSONDocument::fromJson() my jsonString contains : { "extensions" : { ".7z" : ":/mime/7zip.png", ".ace" : ":/mime/ace.png", ".ai" : ":/mime/ai.png", ".eps" : ":/mime/ai.png", ".alg" : ":/mime/algobox.png", ".rar" : ":/mime/archive.png", ".aiff" : ":/mime/audio-x-generic.png"}. (there is more data but I think you get it).

The program doesn't stop unexpectedly but listeCle.size() is always 0. I tried to access directly to ext[".7z"].toString() but I still get "" as a result.

I probably made an enormous mistake, but until now that's the only JSON parsing that fails in the program.

Would you have any explanation or clue ?

Thank you for everything

like image 755
Marc Delerue Avatar asked Aug 06 '26 18:08

Marc Delerue


1 Answers

So the JSON was not valid. I recommend using http://jsonformatter.curiousconcept.com/ in the future, it's a great website.

{
    "extensions":{
        ".7z":":/mime/7zip.png",
        ".ace":":/mime/ace.png",
        ".ai":":/mime/ai.png",
        ".eps":":/mime/ai.png",
        ".alg":":/mime/algobox.png",
        ".rar":":/mime/archive.png",
        ".aiff":":/mime/audio-x-generic.png"
    }
}
like image 130
Iuliu Avatar answered Aug 08 '26 10:08

Iuliu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!