QT开发中文网

qt解析json,json包含对象以及数组对象

在 Qt 中解析 JSON,包含对象以及数组对象的情况,你可以使用 QJsonDocumentQJsonObjectQJsonArray 类来实现。下面是一个示例代码,演示如何解析包含对象和数组对象的 JSON:

// 假设有一个包含对象和数组对象的 JSON 字符串
QString jsonString = R"({
    "name": "Alice",
    "age": 25,
    "skills": ["C++", "Qt", "Python"],
    "friends": [
        {"name": "Bob", "age": 30},
        {"name": "Charlie", "age": 28}
    ]
})";

// 将 JSON 字符串转换为 QJsonDocument 对象
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());

// 检查是否转换成功以及是否为对象类型
if (jsonDoc.isObject()) {
    // 获取根节点对象
    QJsonObject jsonObject = jsonDoc.object();
    
    // 解析简单属性值
    QString name = jsonObject["name"].toString();
    int age = jsonObject["age"].toInt();
    
    qDebug() << "Name: " << name;
    qDebug() << "Age: " << age;

    // 解析数组属性值
    if (jsonObject.contains("skills") && jsonObject["skills"].isArray()) {
        QJsonArray skillsArray = jsonObject["skills"].toArray();
        QStringList skills;
        
        for (const auto& skillValue : skillsArray) {
            if (skillValue.isString()) {
                QString skill = skillValue.toString();
                skills.append(skill);
            }
        }
        
        qDebug() << "Skills: ";
        for(const auto& skill : skills) {
            qDebug() << skill;
        }
    }

    // 解析包含对象的数组属性值
    if (jsonObject.contains("friends") && jsonObject["friends"].isArray()) {
        QJsonArray friendsArray = jsonObject["friends"].toArray();
        
        for (const auto& friendValue : friendsArray) {
            if (friendValue.isObject()) {
                QJsonObject friendObject = friendValue.toObject();
                
                QString friendName = friendObject["name"].toString();
                int friendAge = friendObject["age"].toInt();

                qDebug() << "Friend Name: " << friendName;
                qDebug() << "Friend Age: " << friendAge;
            }
        }
    }
}

以上代码将解析 JSON 字符串并提取其中的属性值。你可以根据实际的 JSON 结构来调整代码以满足你的需求。

希望这个例子能够对你有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=10714

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?