QT解析json数据

发布时间:2024年01月22日

头文件

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

jsonObjectToMap

将Json对象转换成map

QVariantMap MainWindow:: jsonObjectToMap(const QJsonObject &jsonObject)
{
    QVariantMap map;
    for (const QString &key : jsonObject.keys()) {
        QJsonValue value = jsonObject[key];
        if (value.isString()) {
            map[key] = value.toString();
        } else if (value.isDouble()) {
            map[key] = value.toDouble();
        } else if (value.isBool()) {
            map[key] = value.toBool();
        } else if (value.isArray()) {
            QJsonArray array = value.toArray();
            QVariantList list;
            for (int i = 0; i< array.size(); ++i) {
                list.append(array[i].toVariant());
            }
            map[key] = list;
        } else if (value.isObject()) {
            map[key] = jsonObjectToMap(value.toObject());
        }
    }
    return map;
}

parseJson

将Json文件转换成Json对象,再转换成map

void MainWindow::parserJson()
{   
    QFile file("/home/zyt/mysettings/test.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open file:"<< file.errorString();
        return ;
    }

    // 读取 JSON 文件内容
    QByteArray jsonData = file.readAll();
    file.close();

    // QByteArray jsonData = R"({"name":"John","age":30,"city":"New York","isMarried":true,"hobbies":["reading","traveling"],"address":{"street":"123 Main St","zip":12345}})";

    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &error);

    if (error.error != QJsonParseError::NoError) {
        qWarning() << "JSON parse error:"<< error.errorString();
        return ;
    }

    QJsonObject jsonObject = jsonDoc.object();
    QVariantMap map = jsonObjectToMap(jsonObject);

    // 使用 QVariantMap
    for (const QString &key : map.keys()) {
        qDebug()<< key << ":"<< map[key];
    }
}

结果

{
    "squadName": "Super hero squad",
    "homeTown": "Metro City",
    "formed": 2016,
    "secretBase": "Super tower",
    "active": true,
    "members": [
      {
        "name": "Molecule Man",
        "age": 29,
        "secretIdentity": "Dan Jukes",
        "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
      },
      {
        "name": "Madame Uppercut",
        "age": 39,
        "secretIdentity": "Jane Wilson",
        "powers": [
          "Million tonne punch",
          "Damage resistance",
          "Superhuman reflexes"
        ]
      },
      {
        "name": "Eternal Flame",
        "age": 1000000,
        "secretIdentity": "Unknown",
        "powers": [
          "Immortality",
          "Heat Immunity",
          "Inferno",
          "Teleportation",
          "Interdimensional travel"
        ]
      }
    ]
  }

在这里插入图片描述

文章来源:https://blog.csdn.net/qq_40896190/article/details/135744339
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。