ZBLOG

qt 解析出{"buzzer":"OFF","fan":"OFF","led":"OFF","humidity":38,"temperature":22,"light":0,"proximity":0,"co_value":871,"infrared":0}中内容 std::string str = {"device_id":"673db461ef99673c8acec2c4_home_3861","shadow":[{"service_id":"attribute","desired...

要解析你提供的JSON字符串,可以使用Qt的QJsonDocumentQJsonObjectQJsonArray类。这些类提供了方便的方法来处理JSON数据。

以下是一个示例代码,演示如何解析给定的JSON字符串并提取相应的数据:

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

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

    // 你的 JSON 字符串
    std::string str = R"({"device_id":"673db461ef99673c8acec2c4_home_3861","shadow":[{"service_id":"attribute","desired":{"properties":null,"event_time":null},"reported":{"properties":{"buzzer":"OFF","fan":"OFF","led":"OFF","humidity":38,"temperature":22,"light":0,"proximity":0,"co_value":871,"infrared":0},"event_time":"20241126T050051Z"},"version":3058}]})";

    // 将 std::string 转换为 QString
    QString jsonString = QString::fromStdString(str);

    // 解析 JSON 字符串
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
    
    if (jsonDoc.isNull()) {
        qDebug() << "Failed to create JSON doc.";
        return -1;
    }

    // 确保文档是对象类型
    if (!jsonDoc.isObject()) {
        qDebug() << "JSON is not an object.";
        return -1;
    }

    QJsonObject jsonObj = jsonDoc.object();

    // 获取 device_id
    QString deviceId = jsonObj["device_id"].toString();
    qDebug() << "Device ID:" << deviceId;

    // 获取 shadow 数组
    QJsonArray shadowArray = jsonObj["shadow"].toArray();

    for (const auto& item : shadowArray) {
        QJsonObject shadowObj = item.toObject();
        
        // 获取 reported 对象
        QJsonObject reportedObj = shadowObj["reported"].toObject();
        
        // 获取 properties 对象中的值
        QJsonObject propertiesObj = reportedObj["properties"].toObject();
        
        QString buzzerState = propertiesObj["buzzer"].toString();
        QString fanState = propertiesObj["fan"].toString();
        QString ledState = propertiesObj["led"].toString();
        int humidityValue = propertiesObj["humidity"].toInt();
        int temperatureValue = propertiesObj["temperature"].toInt();

        qDebug() << "Buzzer:" << buzzerState;
        qDebug() << "Fan:" << fanState;
        qDebug() << "LED:" << ledState;
        qDebug() << "Humidity:" << humidityValue;
        qDebug() << "Temperature:" << temperatureValue;
        
         // 其他属性可以按照需求继续获取...
     }
     
     return a.exec();
}

在这个例子中,我们首先将标准字符串转换为 QString。然后,我们用 QJsonDocument::fromJson() 函数将其解析成 JSON 文档。如果解析成功,我们进一步提取 device_idshadow 数组中的信息,最终打印出相关内容。

确保包含必要的头文件,并在你的项目中链接 Qt 的核心和网络模块(如果需要)。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?