1.概要
2.代码
//#include "mainwindow.h"#include <QApplication>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
//读取json数据的配置文件int main(int argc, char *argv[])
{QApplication a(argc, argv);QString fileName="test.txt";//MainWindow w;//w.show();// 创建一个 QJsonObjectQJsonObject jsonObject;jsonObject["user"] = QJsonObject {{"name", "John Doe"},{"age", 30},{"email", "johndoe@example.com"}};// 将 QJsonObject 转换为 QJsonDocumentQJsonDocument jsonDoc(jsonObject);// 写入文件QFile file(fileName);if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {file.write(jsonDoc.toJson(QJsonDocument::Indented)); // 缩进格式化输出file.close();}return a.exec();
}
3.运行结果
3.1 test.txt
{
"user": {
"age": 30,
"email": "johndoe@example.com",
"name": "John Doe"
}
}