QT 读取Json 配置文件

{
    QString ProjectPath = "";
    QString ConfigPath = ".json";
    const char* PathEnvVar = getenv("");
    if (PathEnvVar != nullptr) {
        ProjectPath = PathEnvVar;
        ConfigPath = ProjectPath + "/.json";
    }
    if (!QFile::exists(ConfigPath)) {
        qCritical()<< __func__ << " NOT EXIST!";
    }
    QFile ConfigFile(ConfigPath);

    QString jsonContent;

    // Open ConfigFile File
    if (ConfigFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // Read JSON Content
        jsonContent = ConfigFile.readAll();
        // Close ConfigFile File
        ConfigFile.close();
    } else {
        qCritical()<< __func__ << " ConfigFile Not Open";
    }

    QJsonParseError err_rpt;
    QJsonDocument  root_Doc = QJsonDocument::fromJson(jsonContent.toUtf8(), &err_rpt);
    if(err_rpt.error != QJsonParseError::NoError)
    {
        qDebug() <<__func__<< "JSON error";
    }
    else
    {
        QJsonObject root_Obj = root_Doc.object();
        QJsonValue result_Value = root_Obj.value("results");
        if(result_Value.isArray())
        {
            QJsonObject result_Obj = result_Value.toArray().at(0).toObject();
            for(QJsonObject::iterator it = result_Obj.begin(); it != result_Obj.end(); it++)
            {
                if(it.key() == "" || it.key() == "")
                {
                    continue;
                }
                else{
                    QJsonObject warningKey = result_Obj.value(it.key()).toObject();
                    int Id = warningKey.value("id").toString().toInt(nullptr,16);
                    QString Title = warningKey.value("title").toString();
                }
            }
            qDebug() << " " ;
        }
    }
}
posted @ 2024-07-01 14:14  Azuki_op  阅读(105)  评论(0)    收藏  举报