1.概要
要做一个json的读取功能,先做一个原型,然后在实际的工程中套用
2.代码
2.1 main.cpp
#include "widget.h"
#include "inijsonparams.h"
#include <QApplication>
int main(int argc, char *argv[])
{
IniJsonParams iniJsonParams;
//iniJsonParams.save();
iniJsonParams.load();
//QApplication a(argc, argv);
//Widget w;
//w.show();
//return a.exec();
qDebug() << "Hello, World!";
return 0;
}
2.2 datamod.h
#ifndef DATAMOD_H
#define DATAMOD_H
#include <QString>
#include <QList>
class DataMod
{
public:
DataMod();
QString name;
int age;
QString email;
QList<QString> hobbies;
void myView();
};
#endif // DATAMOD_H
2.3 datamod.cpp
#include "datamod.h"
#include <QDebug>
DataMod::DataMod() {}
void DataMod::myView(){
qDebug() << "Hello, World!";
qDebug() << "name:"<<this->name;
qDebug() << "age:"<<this->age;
qDebug() << "email:"<<this->email;
for(int i=0;i<this->hobbies.count();i++){
qDebug() << "hobbies"<<i<<":"<<this->hobbies[i];
}
}
2.4 inijsonparams.h
#ifndef INIJSONPARAMS_H
#define INIJSONPARAMS_H
class IniJsonParams
{
public:
IniJsonParams();
//private:
void load();
void save();
};
#endif // INIJSONPARAMS_H
2.5 inijsonparams.cpp
#include "inijsonparams.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include "datamod.h"
IniJsonParams::IniJsonParams() {}
void IniJsonParams::load(){
DataMod dm;
QString fileName="test.txt";
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
//输出log
return;
}
// 读取文件内容
QByteArray jsonData = file.readAll();
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &jsonError);
QJsonObject obj = jsonDoc.object();
QJsonObject us = obj["user"].toObject();
dm.name = us["name"].toString();
dm.age = us["age"].toInt();
dm.email = us["email"].toString();
QJsonArray array = us["hobbies"].toArray();
for(int i=0;i<array.count();i++){
dm.hobbies.append(array[i].toString());
}
dm.myView();
}
void IniJsonParams::save(){
QString fileName="test.txt";
// 创建一个 QJsonObject
QJsonObject jsonObject;
QJsonObject user;
user.insert("name","John Doe");
user.insert("age",30);
user.insert("email","johndoe@example.com");
QJsonArray hobbiesArray;
hobbiesArray.append("hiking");
hobbiesArray.append("reading");
user.insert("hobbies", hobbiesArray);
jsonObject.insert("user",user);
//jsonObject["user"].toObject().insert("hobbies", hobbiesArray);
// 将 QJsonObject 转换为 QJsonDocument
QJsonDocument jsonDoc(jsonObject);
// 写入文件
QFile file(fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
file.write(jsonDoc.toJson(QJsonDocument::Indented)); // 缩进格式化输出
file.close();
}
}
3.运行结果
3.1 读的结果
Hello, World!
name: "John Doe"
age: 30
email: "johndoe@example.com"
hobbies 0 : "hiking"
hobbies 1 : "reading"
Hello, World!
3.2 写的结果(test.txt)
{
"user": {
"age": 30,
"email": "johndoe@example.com",
"hobbies": [
"hiking",
"reading"
],
"name": "John Doe"
}
}