欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > qt-C++笔记之json文件内容操作完整例程

qt-C++笔记之json文件内容操作完整例程

2024/10/24 4:44:18 来源:https://blog.csdn.net/weixin_43297891/article/details/140597203  浏览:    关键词:qt-C++笔记之json文件内容操作完整例程

qt-C++笔记之json文件内容操作完整例程

code review!

文章目录

  • qt-C++笔记之json文件内容操作完整例程
    • 1.运行输出
    • 2.运行后的test.json文件内容
    • 3.main.cpp

1.运行输出

读取到的 JSON 对象: {"Array": ["Item1","Item2"],"Name": "Example","Value": 42
}修改后的 JSON 对象: {"Array": ["Item1","Item2","Item3"],"Modified": true,"Name": "Modified Example","Value": 42
}

2.运行后的test.json文件内容

{"Array": ["Item1","Item2","Item3"],"Modified": true,"Name": "Modified Example","Value": 42
}

3.main.cpp

#include <QCoreApplication>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QFile>
#include <QIODevice>
#include <QDebug>// 函数:从文件读取 JSON 对象
QJsonObject readJsonFromFile(const QString &filePath) {QFile file(filePath);if (!file.open(QIODevice::ReadOnly)) {qWarning() << "无法打开文件进行读取:" << filePath;return QJsonObject();}QByteArray jsonData = file.readAll();file.close();QJsonDocument doc = QJsonDocument::fromJson(jsonData);if (doc.isNull()) {qWarning() << "解析 JSON 失败。";return QJsonObject();}return doc.object();
}// 函数:将 JSON 对象写入文件
void writeJsonToFile(const QString &filePath, const QJsonObject &jsonObject) {QJsonDocument doc(jsonObject);QFile file(filePath);if (!file.open(QIODevice::WriteOnly)) {qWarning() << "无法打开文件进行写入:" << filePath;return;}file.write(doc.toJson());file.close();
}int main(int argc, char *argv[]) {QCoreApplication a(argc, argv);QString filePath = "test.json";// 创建并写入初始 JSON 对象QJsonObject initialObj;initialObj["Name"] = "Example";initialObj["Value"] = 42;QJsonArray array;array.append("Item1");array.append("Item2");initialObj["Array"] = array;// 将初始 JSON 对象写入文件writeJsonToFile(filePath, initialObj);// 从文件读取 JSON 对象QJsonObject readObj = readJsonFromFile(filePath);// 打印读取到的 JSON 对象qDebug().noquote() << "读取到的 JSON 对象:" << QJsonDocument(readObj).toJson(QJsonDocument::Indented);// 修改读取到的 JSON 对象readObj["Modified"] = true;readObj["Name"] = "Modified Example";QJsonArray newArray = readObj["Array"].toArray();newArray.append("Item3");readObj["Array"] = newArray;// 将修改后的 JSON 对象再次写入文件writeJsonToFile(filePath, readObj);// 再次从文件读取修改后的 JSON 对象QJsonObject modifiedReadObj = readJsonFromFile(filePath);// 打印修改后的 JSON 对象qDebug().noquote() << "修改后的 JSON 对象:" << QJsonDocument(modifiedReadObj).toJson(QJsonDocument::Indented);return a.exec();
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com