20240822 qt与json
明昧 Lv7

JSON

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,使用键值对来表示数据。JSON 格式确实以键值对的形式组织数据,常用于数据的存储和传输。下面是一些 JSON 格式的简单例子:

简单的 JSON 对象

1
2
3
4
5
{
"name": "Alice",
"age": 30,
"isStudent": false
}

包含数组的 JSON 对象

1
2
3
4
{
"name": "Bob",
"hobbies": ["reading", "traveling", "swimming"]
}

嵌套的 JSON 对象

1
2
3
4
5
6
7
8
9
10
11
12
{
"employee": {
"name": "Charlie",
"age": 28,
"address": {
"street": "123 Main St",
"city": "Anytown",
"postalCode": "12345"
},
"skills": ["C++", "Python", "Java"]
}
}

在 Qt 中的 JSON 对象

在 Qt 中,可以使用 QJsonObjectQJsonArray 类来创建和操作 JSON 数据。以下是如何在 Qt 中创建和读取复杂 JSON 对象的示例。

创建 JSON 对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QFile>
#include <QString>

void createJson()
{
QJsonObject address; // 创建地址对象
address["street"] = "123 Main St";
address["city"] = "Anytown";
address["postalCode"] = "12345";

QJsonArray skills; // 创建技能数组
skills.append("C++");
skills.append("Python");
skills.append("Java");

QJsonObject employee; // 创建员工对象
employee["name"] = "Charlie";
employee["age"] = 28;
employee["address"] = address;
employee["skills"] = skills;

QJsonDocument document(employee); // 创建 JSON 文档
QByteArray jsonData = document.toJson(); // 将 JSON 文档转换为字节数组

// 将 JSON 数据写入文件
QFile file("employee.json");
if (file.open(QIODevice::WriteOnly))
{
file.write(jsonData);
file.close();
}
}

读取 JSON 对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QString>

void readJson()
{
QFile file("employee.json");
if (!file.open(QIODevice::ReadOnly)) // 打开文件
{
return; // 如果打开失败则返回
}

QByteArray jsonData = file.readAll(); // 读取所有 JSON 数据
file.close(); // 关闭文件

QJsonDocument document = QJsonDocument::fromJson(jsonData); // 将字节数组转换为 JSON 文档
if (document.isObject()) // 检查文档是否是一个对象
{
QJsonObject employee = document.object(); // 获取 JSON 对象

QString name = employee["name"].toString(); // 获取姓名
int age = employee["age"].toInt(); // 获取年龄
QJsonObject address = employee["address"].toObject(); // 获取地址对象
QString street = address["street"].toString(); // 获取街道
QString city = address["city"].toString(); // 获取城市
QString postalCode = address["postalCode"].toString(); // 获取邮政编码

QJsonArray skills = employee["skills"].toArray(); // 获取技能数组
QStringList skillList;
for (const QJsonValue &skill : skills) // 遍历技能数组
{
skillList.append(skill.toString());
}

// 输出读取的信息
qDebug() << "Name:" << name;
qDebug() << "Age:" << age;
qDebug() << "Address:" << street << city << postalCode;
qDebug() << "Skills:" << skillList;
}
}
 Comments
Comment plugin failed to load
Loading comment plugin
Powered by Hexo & Theme Keep
Unique Visitor Page View