浮叶蓝空的博客
分享学习心得,记录学习笔记
文章:
84
访问:
526142
登录
关于
首页
今天是:
2025年09月09日 星期二
类别
PHP(39)
其他笔记(20)
Java(1)
C++(17)
mysql(2)
JavaScript(4)
近期文章
Linux下Cmake引用第三方静态库示例
Linux下使用Cmake构建静态库示例
Ubuntu设置自动挂载硬盘,挂载U盘
压力测试工具Apache JMeter基本使用
使用PHP脚本借助FFmpeg一键合并视频
Shell中的>、1>、2>、2>&1、&>详解
PHP开启多进程实现异步非阻塞并行执行任务
博主推荐
PHP实现文件下载接口
Qt读写注册表,C++读写注册表
PHP动态修改配置文件,存储为文件
MySql常用语法
Powershell远程连接
PHP从字符串中获取需要的内容部分
封装PHP的HTTP请求
Qt读写json
fuyelk
2021年01月07日
3299
##### Qt读写json,QJsonObject、QJsonDocument解析Json ### 1. 所需头文件 ```cpp #include <QDebug> // debug #include <QJsonDocument> // Json文档 #include <QJsonObject> // Json对象 #include <QJsonParseError> // Json异常捕捉 #include <QFile> // 文件读写 ``` ### 2. 写Json文件 ```cpp // 将Json写入文件 void writeJson() { QJsonObject userInfo; userInfo.insert("id",10); userInfo.insert("name","zhangsan"); userInfo.insert("mobile","18888888888"); userInfo.insert("gender","男"); QJsonObject testJson; testJson.insert("code",1); testJson.insert("msg","用户信息"); testJson.insert("data",userInfo); QJsonDocument document; document.setObject(testJson); QFile file("./test.json"); if (file.open(QIODevice::WriteOnly)) { file.write(document.toJson()); file.close(); qDebug() << "写入成功"; } qDebug() << "操作完成"; } ``` ### 3. 产生Json ```json { "code": 1, "msg": "用户信息", "data": { "gender": "男", "id": 10, "mobile": "18888888888", "name": "zhangsan" } } ``` ### 4. 读Json文件 ```cpp // 从文件读取Json void readJson() { QString json; QFile file("./test.json"); if (file.open(QIODevice::ReadOnly)) { json = file.readAll(); file.close(); } QJsonParseError error; QJsonDocument document = QJsonDocument::fromJson(json.toUtf8(),&error); // 字符串没有错误 if (!document.isEmpty() && (error.error == QJsonParseError::NoError)) { // 转为Json对象 QJsonObject json = document.object(); QJsonValue code = json.value("code"); QJsonValue data = json.value("data"); // 检查数据,模拟校验接口数据 if (code.isUndefined() || 1 != code.toDouble() || data.isUndefined() || !data.isObject()) { qDebug() << "数据有误"; exit(100); } // 取出data信息 QJsonObject user = data.toObject(); QJsonValue checkId = user.value("id"); QJsonValue checkName = user.value("name"); QJsonValue checkMobile= user.value("mobile"); QJsonValue checkGender= user.value("gender"); // 检查接口数据 if (checkId.isUndefined() || checkName.isUndefined() || checkMobile.isUndefined() || checkGender.isUndefined()) { qDebug() << "接口有误"; exit(100); } int id = checkId.toInt(); QString name = checkName.toString(); QString mobile = checkMobile.toString(); QString gender = checkGender.toString(); // 检查每一项配置 if (name.isEmpty() || mobile.isEmpty() || gender.isEmpty()) { qDebug() << "字段不能为空"; exit(100); } qDebug() << "name is :" << id; qDebug() << "name is :" << name; qDebug() << "mobile is :" << mobile; qDebug() << "gender is :" << gender; } qDebug() << "读取完成"; } ``` ### 5. 完成
上一篇:
PHP启动程序不等待执行结果
下一篇:
Qt读写ini配置文件,QSetting
0人点赞
登录后评论
友情链接
doywb
2018-2025 Copyright© 米灵尔 浮叶蓝空
豫ICP备15007436号-1
豫公网安备 41152302000146号