【问题标题】:C++ Qt unable to parse JSON array correctlyC++ Qt 无法正确解析 JSON 数组
【发布时间】:2018-11-01 14:37:50
【问题描述】:

我正在尝试使用 Qt 解析 json,但没有成功。这是我从服务器获得的输出:

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

从这个简单的 php 生成的位置:

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

$data 是一个包含您在上面看到的值的数组。我在 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);
        }

    }

}

这里有什么问题?


请注意qDebug() &lt;&lt; QString{responsedata}; 打印"[{\"anni\":2019},{\"anni\":2018},{\"anni\":2017}]"

【问题讨论】:

    标签: c++ json qt qt-creator


    【解决方案1】:

    您的字段anni 的值是一个整数。使用成员函数toString 不会将其转换为字符串表示形式。它将返回 NULL。 http://doc.qt.io/qt-5/qjsonvalue.html#toString

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

    【讨论】:

    • 谢谢!我误解了toString()的用法,我以为它可以将字段转换为字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2012-08-12
    • 2021-09-24
    相关资源
    最近更新 更多