今天又要用Json文件了,留个笔记方便日后查看
void MainWindow::ReadFile() {
QVector<Time> Data = {};
Time t_Data;
QString fileName = "D://my.json";
QFile file(fileName);
QFile loadFile(fileName);
if (!loadFile.open(QIODevice::ReadOnly)) {
return;
}
QByteArray allData = loadFile.readAll();
loadFile.close();
QJsonParseError jsonerror;
QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &jsonerror));
if (jsonerror.error != QJsonParseError::NoError) {
return;
}
QJsonObject Obj1 = jsonDoc.object();
QJsonObject Obj2 = jsonDoc.object();
QJsonObject Obj3 = jsonDoc.object();
for (int i = 0; i < Obj1.keys().size(); i++) {
QJsonObject Obj2 = Obj1.value(Obj1.keys().at(i)).toObject();
if(Obj2.keys().size() != 24) {
return;
}
for(int j = 0; j < Obj2.keys().size(); j++) {
QJsonObject Obj3 = Obj2.value(Obj2.keys().at(j)).toObject();
t_Data.HeighTime = Obj3["HeighTime"].toInt();
t_Data.MediumTime = Obj3["MediumTime"].toInt();
t_Data.LowTime = Obj3["LowTime"].toInt();
t_Data.NoTime = Obj3["NoTime"].toInt();
Data.append(t_Data);
}
}
for(int i = 0; i < Data.size(); i++) {
qDebug() << i << Data[i].HeighTime << Data[i].LowTime << Data[i].MediumTime << Data[i].NoTime;
}
}
void MainWindow::WriteFile() {
QJsonObject jsonData, jsonHour, obj1;
QDate date = QDate::currentDate();
QString dateStr = date.toString("yyyy-M-d");
for (int i = 0; i < 24; i++) {
QString HourStr = QString("Data%1").arg(i);
QString dataStr = date.toString("yyyy-M-d");
obj1["HeighTime"] = 5;
obj1["MediumTime"] = 6;
obj1["LowTime"] = 8;
obj1["NoTime"] = 6;
jsonHour[HourStr] = obj1;
}
jsonData[dateStr] = jsonHour;
QString fileName = "D://my.json";
QFile file(fileName);
QFileInfo fi(fileName);
QString backupFileName = fi.absolutePath() + "/record_backup.json";
if (file.exists()) {
if (QFile::exists(backupFileName)) {
QFile::remove(backupFileName);
}
QFile::copy(fileName, backupFileName);
}
if (!file.open(QIODevice::WriteOnly)) {
return;
}
QJsonDocument jsonDoc(jsonData);
file.resize(0);
file.write(jsonDoc.toJson());
file.flush();
file.close();
}
|