Qt json
#include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QJsonValue> #include <QFile> #include <QIODevice> #include <QDebug> // 写入JSON数据到文件 void writeJson() { // 创建一个QJsonObject QJsonObject jsonObj; jsonObj["name"] = "John Doe"; jsonObj["age"] = 30; jsonObj["email"] = "johndoe@example.com"; // 创建一个QJsonArray QJsonArray jsonArray; jsonArray.append("item1"); jsonArray.append("item2"); jsonArray.append("item3"); // 将QJsonArray添加到QJsonObject jsonObj["items"] = jsonArray; // 创建QJsonDocument QJsonDocument jsonDoc(jsonObj); // 写入到文件 QFile jsonFile("data.json"); if (jsonFile.open(QIODevice::WriteOnly)) { jsonFile.write(jsonDoc.toJson()); jsonFile.close(); } } // 读取JSON数据 void readJson() { QFile jsonFile("data.json"); if (jsonFile.open(QIODevice::ReadOnly)) { QByteArray jsonData = jsonFile.readAll(); // 解析JSON数据 QJsonDocument jsonDoc(QJsonDocument::fromJson(jsonData)); QJsonObject jsonObj = jsonDoc.object(); // 读取数据 qDebug() << "Name:" << jsonObj["name"].toString(); qDebug() << "Age:" << jsonObj["age"].toInt(); qDebug() << "Email:" << jsonObj["email"].toString(); // 读取数组 QJsonArray jsonArray = jsonObj["items"].toArray(); for (const QJsonValue &value : jsonArray) { qDebug() << "Item:" << value.toString(); } jsonFile.close(); } } int main() { // 写入JSON数据 writeJson(); // 读取JSON数据 readJson(); return 0; }
##################
QQ 3087438119