-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfile_repository.cpp
More file actions
86 lines (69 loc) · 2.23 KB
/
file_repository.cpp
File metadata and controls
86 lines (69 loc) · 2.23 KB
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
//
// Created by Admin on 5/25/2023.
//
#include "file_repository.h"
#include <plog/Log.h>
bool FileRepository::writeJsonArr(const QString &file_name_, const QJsonArray &data_) {
QFile file(file_name_);
if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
PLOGE<< "File cannot be opened" << Qt::endl;
return false;
}
const QByteArray content = file.readAll();
file.resize(0); // Clear the file content
QJsonDocument doc = QJsonDocument::fromJson(content);
QJsonArray data_json;
if (!doc.isNull() && doc.isArray()) {
data_json = doc.array();
}
for (const auto &data: data_) {
data_json.append(data);
}
doc.setArray(data_json);
file.write(doc.toJson());
file.close();
return true;
}
bool FileRepository::readJson(const QString &filePath, QJsonObject &jsonObject) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
PLOGE << "Failed to open file for reading:" << file.errorString();
return false;
}
const QByteArray json_data = file.readAll();
file.close();
QJsonParseError parse_error;
const QJsonDocument json_doc = QJsonDocument::fromJson(json_data, &parse_error);
if (parse_error.error != QJsonParseError::NoError)
{
PLOGE << "Failed to parse JSON:" << parse_error.errorString();
return false;
}
jsonObject = json_doc.object();
return true;
}
bool FileRepository::readJsonArr(const QString &filePath, QJsonArray &jsonObject) {
QFile file(filePath);
if (!file.exists()) {
PLOGE<< "File not found" << Qt::endl;
return false;
}
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
PLOGE << "Failed to open file for reading:" << file.errorString();
return false;
}
const QByteArray json_data = file.readAll();
file.close();
QJsonParseError parse_error;
const QJsonDocument json_doc = QJsonDocument::fromJson(json_data, &parse_error);
if (parse_error.error != QJsonParseError::NoError)
{
PLOGE << "Failed to parse JSON:" << parse_error.errorString();
return false;
}
jsonObject = json_doc.array();
return true;
}
FileRepository::FileRepository() {}