JSON文件读写
JSON文件读写涉及的类:QJsonArray QJsonDocument QJsonObject QJsonParseError
数据读取流程:
Qfile-QByteArray-QJsonDocument-QJsonObject-QJsonValue
数据写入就是数据读取的逆过程。
QJsonObject内部存储json结构文件:
- value(“key”)方法返回QJsonValue类,或者直接通过重载[]方法,使用obj[“key”]得到对应的QJsonValue
- 当然也可以通过迭代器遍历每一个key
QJsonValue存储key对应的value:
- isArray()方法判断是否是一个列表
- toArray()方法返回一个列表对应的QJsonValue数组
QJsonArray存储列表类型的值,通过[]运算符/at()操作取得单个QJsonValue(这里的QJsonValue指的是每一个列表项里面的键值对),再转成QJsonObject就可以进行里面的key/value读取,详见复杂json写入章节
相反的,QJsonArray可以直接调用insert插入obj对象,然后再
简单json读取
{
"success": "1",
"result": {
"timestamp": "1542456793",
"datetime_1": "2018-11-17 20:13:13",
"datetime_2": "2018年11月17日 20时13分13秒",
"week_1": "6",
"week_2": "星期六",
"week_3": "周六",
"week_4": "Saturday"
}
}
// qfile读取文件转换为QByteArray
QFile file("./cfg/test.json");
if(!file.open(QIODevice::ReadOnly)){
QMessageBox::about(NULL,"提示","请检查./cfg/test.json文件");
return ;
}
QByteArray allData = file.readAll();
file.close();
// QJsonDocument解析QByteArray
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(allData, &jsonError);
if(jsonError.error != QJsonParseError::NoError){
QMessageBox::about(NULL,"提示","parserRemoteSig.json配置文件解析出错");
return;
}
// 转换成object对象
QJsonObject jsonObj = jsonDoc.object();
// 操作obj对象 .value方法返回QJsonValue ,再调用QJsonValue的toString()方法
QString success = jsonObj.value("success").toString();
QJsonObject result_Obj = jsonObj.value("result").toObject();
复杂json读取(含有列表)
data内包含对象列表
{
"status": "0",
"citye": "changchun",
"city": "长春",
"citycode": "101060101",
"aqi": "50",
"data": [{
"add": "长春",
"aqi": "50",
"pm25": "22",
"per": "优",
"lv": "1"
}, {
"add": "食品厂",
"aqi": "54",
"pm25": "18",
"per": "良",
"lv": "2"
}, {
"add": "客车厂",
"aqi": "52",
"pm25": "20",
"per": "良",
"lv": "2"
}]
}
// 预处理然后转成obj
QJsonObject root_Obj = root_Doc.object();
QString city = root_Obj.value("city").toString();
QString citycode = root_Obj.value("citycode").toString();
QString citye = root_Obj.value("citye").toString();
QString status = root_Obj.value("status").toString();
qDebug() << city + " " + citycode + " " + citye + " " + status;
/* data键取出的值 */
QJsonValue data_Vaule = root_Obj.value("data");
if(data_Vaule.isArray())
{
int nsize = data_Vaule.toArray().size();
for(int idx = 0; idx < nsize; idx++)
{
//将列表里面每一个都转成obj对象
QJsonObject data_Obj = data_Vaule.toArray().at(idx).toObject();
//再用基础方法取出里面的值
QString add = "地址:" + data_Obj.value("add").toString();
QString aqi = " AQI:" + data_Obj.value("aqi").toString();
QString lv = " 空气质量等级:" + data_Obj.value("lv").toString();
QString per = " 空气质量:" + data_Obj.value("per").toString();
QString pm25 = " PM2.5等级:" + data_Obj.value("pm25").toString();
qDebug() << add + aqi + lv + per + pm25;
}
}
简单json写入
// 转换成obj后
QJsonObject jsonObj = jsonDoc.object();
//qDebug()<<jsonObj;
// 将json配置写入结构体
jsonObj.insert("CSDN", "https://blog.csdn.net/houxian1103");
jsonObj.insert("cnblogs", "https://blog.csdn.net/houxian1103");
// 创建Json文档,转换回doc
QJsonDocument root_Doc;
root_Doc.setObject(jsonObj);
// 转换回QByteArray
//QByteArray root_str = root_Doc.toJson(QJsonDocument::Compact); //紧凑格式
QByteArray root_str = root_Doc.toJson(QJsonDocument::Indented); //标准JSON格式 QString strJson(root_str);
// 写入file
QFile file("./cfg/test.json");
if(!file.open(QIODevice::WriteOnly)){
QMessageBox::about(NULL,"提示","请检查./cfg/test.json文件");
return ;
}
if(file.write(root_str)==-1){
QMessageBox::about(NULL,"提示","保存出错");
}
file.close();
复杂json写入
目标内容
{
"status": "ok",
"weather": [{
"date": "2022-07-21",
"cond_txt": "多云",
"cond_code": "101",
"hum": "23",
"tmp_H": "31",
"tmp_L": "25"
}, {
"date": "2022-07-22",
"cond_txt": "晴",
"cond_code": "100",
"hum": "20",
"tmp_H": "33",
"tmp_L": "26"
}, {
"date": "2022-07-23",
"cond_txt": "阵雨",
"cond_code": "107",
"hum": "45",
"tmp_H": "32",
"tmp_L": "25"
}],
"update": "2022-07-21 11:00",
"Blog": "www.baidu.com"
}
QString CreateJson::Create_Array_JSON(void)
{
QJsonObject day0_Obj;
QJsonObject day1_Obj;
QJsonObject day2_Obj;
day0_Obj.insert("date", "2022-07-21");
day0_Obj.insert("cond_txt", "多云");
day0_Obj.insert("cond_code", "101");
day0_Obj.insert("hum", "23");
day0_Obj.insert("tmp_H", "31");
day0_Obj.insert("tmp_L", "25");
day1_Obj.insert("date", "2022-07-21");
day1_Obj.insert("cond_txt", "阵雨");
day1_Obj.insert("cond_code", "107");
day1_Obj.insert("hum", "44");
day1_Obj.insert("tmp_H", "30");
day1_Obj.insert("tmp_L", "26");
day2_Obj.insert("date", "2022-07-22");
day2_Obj.insert("cond_txt", "晴");
day2_Obj.insert("cond_code", "100");
day2_Obj.insert("hum", "20");
day2_Obj.insert("tmp_H", "33");
day2_Obj.insert("tmp_L", "26");
QJsonArray weather_Arr;
weather_Arr.insert(0, day0_Obj);
weather_Arr.insert(1, day1_Obj);
weather_Arr.insert(2, day2_Obj);
QJsonObject root_Obj;
root_Obj.insert("status", "ok");
root_Obj.insert("update", "2022-07-21 11:00");
root_Obj.insert("Blog", "www.wangchaochao.top");
root_Obj.insert("weather", weather_Arr); // 数组作为weather键的值
// 创建Json文档
QJsonDocument root_Doc;
root_Doc.setObject(root_Obj);
QByteArray root_str = root_Doc.toJson(QJsonDocument::Compact); // 紧凑格式
// QByteArray root_str = root_Doc.toJson(QJsonDocument::Indented); //标准JSON格式
// 写入file
QFile file("./cfg/test.json");
if(!file.open(QIODevice::WriteOnly)){
QMessageBox::about(NULL,"提示","请检查./cfg/test.json文件");
return ;
}
if(file.write(root_str)==-1){
QMessageBox::about(NULL,"提示","保存出错");
}
file.close();
}
Yaml文件读写
yaml吸入和返回字符串是string类型而不是QString类型,需要常见转换如下:
String转换到QString:QString::fromStdString(mystr);
QString转换到String:QString::toStdString();
读取
普通读取
Node 是 yaml-cpp 中的核心概念,它用于存储解析后的 yaml 信息。
YAML::Node config = YAML::LoadFile("../config.yaml");
cout << "name:" << config["name"].as<string>() << endl;
cout << "sex:" << config["sex"].as<string>() << endl;
cout << "age:" << config["age"].as<int>() << endl;
cout << "skills c++:" << config["skills"]["c++"].as<int>() << endl;
cout << "skills java:" << config["skills"]["java"].as<int>() << endl;
cout << "skills android:" << config["skills"]["android"].as<int>() << endl;
cout << "skills python:" << config["skills"]["python"].as<int>() << endl;
迭代读取
for(YAML::const_iterator it= config["skills"].begin(); it != config["skills"].end();++it)
{
cout << it->first.as<string>() << ":" << it->second.as<int>() << endl;
}
int main() {
YAML::Node config = YAML::LoadFile("config.yaml");
YAML::Node node = config["dev_cfg"];
for (const auto& setting : communicationSettings) {
std::string node_info = setting["node"].as<std::string>();
int selected = setting["selected"].as<int>();
std::cout << "node: " << node_info << std::endl;
std::cout << "selected: " << selected << std::endl;
std::cout << std::endl;
}
return 0;
}
写入修改和删除
YAML::Node node;
node["NAME"] = ui->lineEdit->text().toStdString();
node["NUM"] = 1;
node["BOOL"] = true;
node["DATE"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss").toStdString();
// 修改
node.remove("NAME");
std::ofstream fout("这里是yaml路径");
fout << node;
fout.close();
QSettings
配置结构
写入
void Widget::on_pushButton_1_clicked()
{
QSettings *settings = new QSettings("App.ini",QSettings::IniFormat);
//ini配置文件默认不支持直接读写中文,需要手动设置下编码格式才行
//configIni->setIniCodec("utf-8");//添上这句就不会中文出现乱码了
//强烈建议统一用utf-8编码,包括代码文件。
// 写入第一组数据
settings->beginGroup("PortInfo");
settings->setValue("name","COM1");
settings->setValue("checkBit","none");
settings->setValue("baudRate",9600);
settings->setValue("dataBits",8);
settings->endGroup();
// 写入第二组数据
settings->beginGroup("PortInfo1");
settings->setValue("name","COM2");
settings->setValue("checkBit","none");
settings->setValue("baudRate",100000);
settings->setValue("dataBits",8);
settings->endGroup();
delete settings;
settings =nullptr;
}
读取
void Widget::on_pushButton_2_clicked()
{
QSettings *settings = new QSettings("App.ini",QSettings::IniFormat);
//configIni->setIniCodec("utf-8");//添上这句就不会出现乱码了
QString group1_name=settings->value("PortInfo/name").toString();
int group1_baudrate=settings->value("PortInfo/BaudRate").toInt();
QString group2_name=settings->value("PortInfo1/name").toString();
int group2_baudrate=settings->value("PortInfo1/BaudRate").toInt();
ui->textEdit->append("组1数据");
ui->textEdit->append(group1_name);
ui->textEdit->append(QString::number(group1_baudrate));
ui->textEdit->append("组2数据");
ui->textEdit->append(group2_name);
ui->textEdit->append(QString::number(group2_baudrate));
}