1

I am trying to parse json with Qt but I have no success. This is the ouput that I get from the server:

[{"anni":2019},{"anni":2018},{"anni":2017}]

Where that's generated from this simple php:

header('Content-Type: application/json');
echo json_encode($data);

The $data is an array containing the values you see above. I am using this piece of code in Qt 5.11.2:

void MainWindow::showYears() {   

    //reply is a QNetworkReply* reply;
    if (reply->error() != QNetworkReply::NoError) {
        //some error managment
    } else {

        auto responsedata = reply->readAll();

        QJsonArray years = QJsonDocument::fromJson(responsedata).array();          
        qDebug() << QString{responsedata};

        for(const QJsonValue& y : years) {
            QJsonObject obj = y.toObject();

            //doing "qDebug() << r" shows that r is "" (empty!)
            auto r = obj["anni"].toString();

            ui->comboBoxP->addItem(r);
        }

    }

}

What's wrong here?


Please note that qDebug() << QString{responsedata}; prints "[{\"anni\":2019},{\"anni\":2018},{\"anni\":2017}]"

1 Answer 1

6

The value for your field anni is an integer. Using the member function toString will not convert it to a string representation. it will return NULL. http://doc.qt.io/qt-5/qjsonvalue.html#toString

Try with: auto r = QString::number(obj["anni"].toInt());

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I misunderstood the usage of toString(), I thought it was able to convert the field to a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.