简体   繁体   中英

Qt JSON: how to get the array elements?

I feel like I'm losing my mind here.

I'm trying to parse a JSON document, and every time I attempt to access an array's element I get the array itself. After some elimination I came up with the following SSCCE:

#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    const QByteArray jsonData {"[1,2]"};

    QJsonParseError error;
    const QJsonDocument jsonDoc {QJsonDocument::fromJson(jsonData, &error)};
    if(error.error != QJsonParseError::NoError)
    {
        qWarning() << error.errorString();
        return -1;
    }
    Q_ASSERT(!jsonDoc.isNull());
    Q_ASSERT(!jsonDoc.isEmpty());

    Q_ASSERT(jsonDoc.isArray());
    const QJsonArray jsonArray {jsonDoc.array()};
    qDebug() << jsonArray.size(); // Expectation: 2, reality: 1
    qDebug() << jsonArray; // Expectation: QJsonArray([1,2]), reality: QJsonArray([[1,2]])

    const QJsonValue jsonValue {jsonArray.at(0)};
    qDebug() << jsonValue.type(); // returns 4 (Array)

    const QJsonArray jsonArray2 {jsonValue.toArray()};
    qDebug() << jsonArray2.size(); // Expectation: 2, reality: 1
    qDebug() << jsonArray2; // Expectation: QJsonArray([1,2]), reality: QJsonArray([[1,2]])

    // ...ad infinitum

    return 0;
}

The thing is, I get this behavior on Qt 5.9.4 and 5.15.1, but NOT on ancient Qt 5.1.1!

On Qt 5.1.1, the result is exactly what I expect: jsonArray.size() returns 2, jsonArray is QJsonArray([1,2]) , and jsonValue.type() is 2 ( Double ).

Obviously the problem is me, because there is NO WAY a bug like this would slip through AND survive for (at least) three years. So the question is, how do I extract the actual values (ie 1 and 2 ) from the array in the aforementioned example using modern Qt versions.

const QJsonArray jsonArray {jsonDoc.array()}; This does not do what you expect. Curly-brace-initialization is really a pita when used for everything where it's not really needed (apart from the non-readability).

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