Files
scuc-qt-course/docs/teaching/examples/json_io/qt_json_parse_write.cpp
T
张宗平 83620c0cf5 教案对齐官方方案书:重写为 5 天 C++/Qt 教学设计,补齐 6 个 Qt 技术缺口示例
- docs/teaching/OUTLINE.md、slides/day1-5.html、index.html:替换此前自定义的
  4 天方案,严格对齐 docs/TRAINING_PLAN_2026.md「C++方向」Day1-5 课堂内容
  (Day6-10 为纯项目实作,不在教案范围)
- docs/teaching/examples/:官方方案书要求但仓库 p03/(wiki 抓取内容) 未覆盖的
  QSS/Model-View/JSON/QThread/QPropertyAnimation/QStateMachine 六个技术点,
  各补一个最小可运行示例 + README 教学文档,均已离屏验证跑通;手工维护,
  不属于 gen_part3.py 生成产物
- 根 CMakeLists.txt:接入 docs/teaching/examples 构建(BUILD_QT_PART 分支内),
  不改动生成器管理的 p01/p03 CMakeLists
- 任务卡改为目标/验收标准/基础知识参考三段式模板,custom.css 配套新增样式
- docs/teaching/PRETEST.md:10 题 10 分钟 C++ 摸底测验,验证教案假定的受众
  基础是否成立,并与 OUTLINE.md §0 的分层预案挂钩
2026-07-02 11:31:44 +08:00

50 lines
2.0 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ============================================================================
// qt_json_parse_write —— 教学补充示例(非 wiki 生成,手工维护)
// 用途:方案书「C++方向 Day3」要求的 JSON 等主流数据格式解析,仓库 p03/ch11
// 原有 wiki 抓取内容只覆盖 QFile/QTextStream/QDataStream,没有 JSON
// 故补一个最小示例。
// 说明:JSON 读写不需要 GUI,用 QCoreApplication 即可,不需要
// QT_QPA_PLATFORM=offscreen,直接 tools/run_qt.sh qt_json_parse_write 即可。
// 配套文档:docs/teaching/examples/json_io/README.md
// ============================================================================
#include <QCoreApplication>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
// 1) 构造一个 JSON 对象(对应课程里“学员信息”这类结构)
QJsonObject student;
student["name"] = QStringLiteral("张三");
student["score"] = 92;
QJsonArray tags;
tags.append(QStringLiteral("Qt"));
tags.append(QStringLiteral("C++"));
student["tags"] = tags;
// 2) 序列化:QJsonObject -> QJsonDocument -> 字节数组(可直接写文件)
QJsonDocument doc(student);
QByteArray bytes = doc.toJson(QJsonDocument::Indented);
qDebug().noquote() << "序列化结果:\n" << bytes;
// 3) 反序列化:字节数组 -> QJsonDocument -> 取值
QJsonDocument parsed = QJsonDocument::fromJson(bytes);
if (!parsed.isNull() && parsed.isObject()) {
QJsonObject obj = parsed.object();
qDebug() << "姓名:" << obj["name"].toString();
qDebug() << "分数:" << obj["score"].toInt();
const QJsonArray parsedTags = obj["tags"].toArray();
for (const QJsonValue& v : parsedTags)
qDebug() << "标签:" << v.toString();
} else {
qDebug() << "JSON 解析失败";
return 1;
}
return 0;
}