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

ナビゲーションに移動 検索に移動
130行目: 130行目:
  #include <QException>
  #include <QException>
  #include <QDebug>
  #include <QDebug>
   
   
  int main(int argc, char *argv[])
  int main(int argc, char *argv[])
189行目: 190行目:
       "imp":["awesome","best","good"]
       "imp":["awesome","best","good"]
     }
     }
}
</syntaxhighlight>
<br><br>
== JSONファイルの編集 ==
以下に示すようなJSONファイルにおいて、<u>appDesc</u>オブジェクトにある<u>description</u>キーの値を変更する。<br>
<syntaxhighlight lang="json">
# Sample.json
{
    "appDesc": {
      "description": "SomeDescription",
      "message": "SomeMessage"
    },
    "appName": {
      "description": "Home",
      "message": "Welcome",
      "imp":["awesome","best","good"]
    }
}
</syntaxhighlight>
<br>
JSONファイルを編集する場合、以下に示す手順に従う。<br>
# <code>QFile</code>クラスを使用して、JSONファイルを読み込む。
# <code>QJsonDocument</code>クラスを使用して読み込んだデータを解析して、JSONオブジェクトに変換する。
# <code>QJsonObject</code>クラスでdescriptionキーの値を変更する。
# <code>QJsonDocument</code>クラスを使用して変更したJSONオブジェクトから新しいJSONドキュメントを作成して、それをファイルに書き込む。
<br>
以下の例では、Sample.jsonファイルからJSONデータを読み込み、appDesc内のdescriptionキーの値をhogeに変更して、同じファイルに変更を保存している。<br>
<syntaxhighlight lang="c++">
#include <QCoreApplication>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QException>
#include <QDebug>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // Sample.josnファイルを開く
    QFile file("Sample.json");
    if (!file.open(QIODevice::ReadOnly)) {
      qWarning("Could not open json file.");
      return -1;
    }
    try {
      // Sample.jsonファイルからJSONデータを読み込む
      QByteArray jsonData = file.readAll();
    }
    catch (QException &ex) {
      qWarning("Could not read json file.");
      file.close();
      return -1;
    }
    file.close();
    // JSONドキュメントを解析
    QJsonDocument document = QJsonDocument::fromJson(jsonData);
    QJsonObject rootObject = document.object();
    // appDescオブジェクトを取得して、descriptionキーの値を変更
    QJsonObject appDescObject = rootObject["appDesc"].toObject();
    appDescObject["description"] = "hoge";  // descriptionキーの値を変更
    // 変更したappDescオブジェクトをrootオブジェクトに格納
    rootObject["appDesc"] = appDescObject;
    // 変更したappDescオブジェクトでJSONドキュメントを更新
    QJsonDocument updatedDocument(rootObject);
    // ファイルに書き出し
    if (!file.open(QIODevice::WriteOnly)) {
      qWarning("ファイルを再度開けませんでした。");
      return -1;
    }
    try {
      file.write(updatedDocument.toJson());
    }
    catch (QException &ex) {
      qWarning("Could not modify json file.");
      file.close();
      return -1;
    }
    file.close();
    return a.exec();
  }
  }
  </syntaxhighlight>
  </syntaxhighlight>

案内メニュー