「Qtの基礎 - JSON」の版間の差分

ナビゲーションに移動 検索に移動
113行目: 113行目:
<br>
<br>
==== 配列オブジェクトの場合 ====
==== 配列オブジェクトの場合 ====
<syntaxhighlight lang="json">
# Sample.json
{
    {
      "description": "SomeDescription",
      "message": "SomeMessage"
    },
    {
      "description": "Home",
      "message": "Welcome",
      "imp":["awesome","best","good"]
    }
}
</syntaxhighlight>
<br>
<syntaxhighlight lang="c++">
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QString>
#include <QDebug>
void readJson()
{
    // Jsonファイルの読み込み
    QFile file("Sample.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "JSONファイルの読み込みに失敗しました" << filePath;
        return;
    }
    QByteArray jsonData = file.readAll();
    // ファイルを閉じる
    file.close();
    QJsonDocument document = QJsonDocument::fromJson(jsonData);
    if (!document.isArray()) {
      qDebug() << "JSONファイルに配列オブジェクトがありません";
      return;
    }
    QJsonArray jsonArray = document.array();
    foreach (const QJsonValue &value, jsonArray) {
        QJsonObject obj = value.toObject();
        QString desc    = obj["description"].toString();
        QString message = obj["message"].toString();
        QString imp    = obj["imp"].isArray();
    }
    // ...略
}
</syntaxhighlight>
<br><br>
<br><br>


案内メニュー