简体   繁体   中英

QT how to parse objects inside an array json

I've got a JSON with the following structure

[{
    "primul": "Thor",
    "alDoilea": "Odin",
    "alTreilea": "Loki"
},

{
    "s": 1,
    "d": 7,
    "hp": 39
},

{
    "1": "sabie",
    "2": "scut",
    "3": "coif"
}
]

Basically it's an array with x objects inside.

I've tried using QVariant to transform the data into a list and then map the elements of the list but it keeps throwing me cannot convert const char to int when using QVariantMap

Where am I going wrong?

Here is my code

QFile file2("../JsonExemplu/exampleArray.json");

    if (!file2.exists()) {
        qDebug()<<"Fisierul nu a fost gasit ";
        exit(1);
    }

    if(!file2.open(QIODevice::ReadOnly)){
        qDebug()<<"Nu s-a putut deschide fisierul JSON ";
        exit(1);
    }

    QTextStream file_text(&file2);
    QString json_string;
    json_string = file_text.readAll();
    file2.close();
    QByteArray json_bytes = json_string.toLocal8Bit();

    auto json_doc=QJsonDocument::fromJson(json_bytes);

    if(!json_doc.isArray()){
        qDebug() << "Formatul nu e de tip arrray.";
        exit(1);
    }

    QJsonArray json_array = json_doc.array();

    if(json_array.isEmpty()){
        qDebug() << "JSON gol";
        exit(1);
    }


    QVariantList root_map = json_array.toVariantList();
    QVariantMap stat_map = root_map["nume"].toMap();
    QVariantMap stat_map2 = root_map["statistici"].toMap();
    QVariantMap stat_map3 = root_map["inventar"].toMap();

    QStringList key_list = stat_map.keys();

    for(int i=0; i< json_array.count(); ++i){
        QString key=key_list.at(i);
        QString stat_val = stat_map[key.toLocal8Bit()].toString();
         qDebug() << key << ": " << stat_val;
    }


}

The problem is that your convert QJsonArray to a list of variants. However you refer to that list as if it's a map - this will, of course, not compile. To fix the problem you need to use the appropriate QList API, ie:

QVariantList root_map = json_array.toVariantList(); // This is a list, not a map!

// There are three items in the list.
// The code below can be put into a loop.
QVariantMap stat_map = root_map.at(0).toMap();
QVariantMap stat_map2 = root_map.at(1).toMap();
QVariantMap stat_map3 = root_map.at(2).toMap();

QStringList key_list = stat_map.keys();

for (int i = 0; i< key_list.count(); ++i)
{
  QString key = key_list.at(i);
  QString stat_val = stat_map[key.toLocal8Bit()].toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM