简易结构体的设计思路
ssk-wh Lv4

编程小记—应对一般的组合结构

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <QDebug>
#include <QString>
#include <QVariant>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>

struct KeyValue {
QString key;
QString value;
};

typedef std::vector<KeyValue> KeyValues;

struct FStruct;
typedef QList<FStruct *> Childs;

// 承载普通的json数据
struct FStruct {
KeyValues list;
QMap<QString, Childs> childMap;

~ FStruct() {
list.clear();
if (!childMap.isEmpty()) {
for (auto clist : childMap.values())
qDeleteAll(clist);
}
}
};

void _dumpFStruct(FStruct *fs, QString node, int depth) {
qDebug() << "dump" << node << ", depth : " << depth;
for (auto kv : fs->list) {
qDebug() << kv.key << " : " << kv.value;
}

if (fs->childMap.isEmpty())
return;

for (auto it = fs->childMap.begin(); it != fs->childMap.end(); ++it) {
auto tag = it.key();
auto childs = it.value();
for (auto child : childs) {
_dumpFStruct(child, tag, depth + 1);
}
}
}

void dumpFStruct(FStruct *fs) {
int depth = 0;
qDebug() << "dump:";
for (auto kv : fs->list) {
qDebug() << kv.key << " : " << kv.value;
}

if (fs->childMap.isEmpty())
return;

for (auto it = fs->childMap.begin(); it != fs->childMap.end(); ++it) {
auto tag = it.key();
auto childs = it.value();
for (auto child : childs) {
_dumpFStruct(child, tag, depth + 1);
}
}
}

QJsonValue convertToJson(FStruct *fs) {
Q_ASSERT(fs);

QJsonObject kvObj;
for (auto kv : fs->list) {
kvObj.insert(kv.key, kv.value);
}

for (auto it = fs->childMap.begin(); it != fs->childMap.end(); ++it) {
auto tag = it.key();
auto childs = it.value();

QJsonArray arr;
for (auto c : childs) {
auto v = convertToJson(c);
arr.append(v);
}
kvObj[tag] = arr;
}

return kvObj;
}

int main(int argc, char *argv[])
{
(void) argc;
(void) argv;

// 一份FStruct结构的数据
FStruct *root = new FStruct;
root->list.push_back({"1", "2"});
{
FStruct *node1 = new FStruct;
node1->list.push_back({"3", "4"});
{
FStruct *node2 = new FStruct;
node2->list.push_back({"5", "6"});
node2->list.push_back({"7", "8"});
node1->childMap["node2"].push_back(node2);

FStruct *node3 = new FStruct;
node3->list.push_back({"9", "10"});
node3->list.push_back({"11", "12"});
node1->childMap["node2"].push_back(node3);
}
root->childMap.insert("node1", Childs() << node1);
}

dumpFStruct(root);

// 转成QJsonObject
auto obj = convertToJson(root);
if (obj.isObject()) {
qDebug() << obj.toObject();
}
}
 Comments