Search code examples
c++jsonqtqt5qtcore

how to decode json in qt


i want to decode following json with qt:

{
 "user": {
  "name": "string"
 }
}

i'm tried to do it with this code, but does not work:

QJsonDocument jsonResponse = QJsonDocument::fromJson(result.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["user"].toArray();
foreach (const QJsonValue & value, jsonArray)
        {
            QJsonObject obj     = value.toObject();
            url          = obj["name"].toString();
        }

Solution

  • This is the culprit:

    QJsonArray jsonArray = jsonObject["user"].toArray();
    

    You are trying to convert the object to an array without any isArray() check. That is, your json does not contain an array therein. Array means [...] in the json world.

    You ought to either use toObject() or change your input json.

    Without json file change, you would write this:

    QJsonDocument jsonResponse = QJsonDocument::fromJson(result.toUtf8());
    QJsonObject jsonObject = jsonResponse.object();
    QJsonObject userJsonObject = jsonObject.value("user").toObject();
    qDebug() << userJsonObject.value("name").toString();