QT解析json数据

QT解析json数据

    • 头文件
    • jsonObjectToMap
    • parseJson
    • 结果

头文件

#include 
#include 
#include 
#include 
#include 

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"
        ]
      }
    ]
  }

QT解析json数据_第1张图片

你可能感兴趣的:(qt,qt,json)