13,005
回編集
107行目: | 107行目: | ||
for (const auto impvalue : impvalues) { // 範囲ループforで取得する場合 | for (const auto impvalue : impvalues) { // 範囲ループforで取得する場合 | ||
vecvalues.push_back(impvalue.toString()); | vecvalues.push_back(impvalue.toString()); | ||
} | |||
} | |||
</syntaxhighlight> | |||
<br><br> | |||
== JSONファイルの作成 == | |||
JSONファイルを作成する場合、以下に示す手順に従う。<br> | |||
# まず、QJsonObjectクラスを使用して、JSONオブジェクトを作成する。 | |||
# 配列の場合は、QJsonArrayクラスを使用してJSON配列を作成した後、それをオブジェクトに追加する。 | |||
# QJsonDocumentクラスを使用してJSONドキュメントを作成した後、それをファイルに書き込む。 | |||
<br> | |||
以下の例では、指定されたJSON構造を持つSample.jsonファイルを生成している。<br> | |||
<br> | |||
<code>QJsonDocument</code>クラスの<code>toJson</code>メソッドは、整形されていないJSONデータを返す。<br> | |||
読みやすい形式で出力する場合は、<code>toJson(QJsonDocument::Indented)</code>メソッドを使用すること。<br> | |||
<syntaxhighlight lang="c++"> | |||
#include <QCoreApplication> | |||
#include <QFile> | |||
#include <QJsonDocument> | |||
#include <QJsonObject> | |||
#include <QJsonArray> | |||
#include <QException> | |||
#include <QDebug> | |||
int main(int argc, char *argv[]) | |||
{ | |||
QCoreApplication a(argc, argv); | |||
// JSONオブジェクトの作成 | |||
QJsonObject jsonObject; | |||
jsonObject["description"] = "Home"; | |||
// JSON配列を定義して値を追加する | |||
QJsonArray impArray; | |||
impArray.append("awesome"); | |||
impArray.append("best"); | |||
impArray.append("good"); | |||
// 配列をオブジェクトに追加 | |||
jsonObject["imp"] = impArray; | |||
// 別のキーと値を追加 | |||
jsonObject["message"] = "YouTube"; | |||
// JSONドキュメントを作成 | |||
QJsonDocument jsonDocument(jsonObject); | |||
try { | |||
// JSONファイルを作成 | |||
QFile file("Sample.json"); | |||
if (!file.open(QIODevice::WriteOnly)) { | |||
qWarning("ファイルを開けませんでした。"); | |||
return -1; | |||
} | |||
file.write(jsonDocument.toJson()); | |||
file.close(); | |||
} | |||
catch (QException &ex) { | |||
qWarning("Could not create json file : " + ex.what()); | |||
return -1; | |||
} | |||
return a.exec(); | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
以下に示すようなJSONファイルが作成される。<br> | |||
<syntaxhighlight lang="json"> | |||
# Sample.json | |||
{ | |||
"appDesc": { | |||
"description": "SomeDescription", | |||
"message": "SomeMessage" | |||
}, | |||
"appName": { | |||
"description": "Home", | |||
"message": "Welcome", | |||
"imp":["awesome","best","good"] | |||
} | } | ||
} | } |