以下是使用Qt的Json库读取和解析上述json文件的示例代码:

#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
#include <QDebug>

int main() {
    QFile file("abc.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Failed to open file.";
        return -1;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
    if (jsonDoc.isNull()) {
        qDebug() << "Failed to parse JSON data.";
        return -1;
    }

    QJsonObject jsonObj = jsonDoc.object();
    int swtnum = jsonObj.value("swtnum").toInt();
    qDebug() << "swtnum: " << swtnum;

    for (int i = 0; i < swtnum; i++) {
        QString swtKey = QString("swt%1").arg(i);
        QJsonObject swtObj = jsonObj.value(swtKey).toObject();
        QString name = swtObj.value("name").toString();
        QString id = swtObj.value("id").toString();
        int portnum = swtObj.value("portnum").toInt();
        qDebug() << "name: " << name;
        qDebug() << "id: " << id;
        qDebug() << "portnum: " << portnum;

        QJsonObject portInfoObj = swtObj.value("portInfo").toObject();
        QStringList portKeys = portInfoObj.keys();
        foreach (QString portKey, portKeys) {
            QJsonObject portObj = portInfoObj.value(portKey).toObject();
            float speed = portObj.value("speed").toDouble();
            int portId = portObj.value("id").toInt();
            int credit = portObj.value("credit").toInt();
            qDebug() << "portKey: " << portKey;
            qDebug() << "speed: " << speed;
            qDebug() << "portId: " << portId;
            qDebug() << "credit: " << credit;
        }
    }

    return 0;
}

这段代码会打印出json文件中的所有数据,你可以根据需要修改代码,将数据存储到相应的变量中。

使用Qt JSON库解析JSON文件示例

原文地址: https://www.cveoy.top/t/topic/O8D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录