JSON是一种简单的轻量级资料交换格式,Qt库为JSON的相关操作提供了完整的类支持,使用JSON决议档案之前需要先通过TextStream
流将档案读入到字符串变量内,然后再通过QJsonDocument
等库对该JSON格式进行决议,以提取出我们所需栏位,
首先创建一个决议档案,命名为config.json
我们将通过代码依次决议这个JSON档案中的每一个自变量,具体决议代码如下:
{
"blog": "https://www.cnblogs.com/lyshark",
"enable": true,
"status": 1024,
"GetDict": {"address":"192.168.1.1","username":"root","password":"123456","update":"2020-09-26"},
"GetList": [1,2,3,4,5,6,7,8,9,0],
"ObjectInArrayJson":
{
"One": ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
"Two": ["Sunday","Monday","Tuesday"]
},
"ArrayJson": [
["192.168.1.1","root","22"],
["192.168.1.2","root","23"],
["192.168.1.3","root","24"],
["192.168.1.4","root","25"],
["192.168.1.5","root","26"]
],
"ObjectJson": [
{"address":"192.168.1.1","username":"admin"},
{"address":"192.168.1.2","username":"root"},
{"address":"192.168.1.3","username":"lyshark"}
]
}
首先实作读写文本档案,通过QT中封装的<QFile>
库可实作对文本档案的读取操作,读取JSON档案可使用该方式.
#include <QCoreApplication>
#include <iostream>
#include <QString>
#include <QTextStream>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonValueRef>
// 传入文本路径,读取并输出
int readonly_string_file(QString file_path)
{
QFile this_file_ptr(file_path);
// 判断档案是否存在
if(false == this_file_ptr.exists())
{
std::cout << "档案不存在" << std::endl;
return 0;
}
/*
* 档案打开属性包括如下
* QIODevice::ReadOnly 只读方式打开
* QIODevice::WriteOnly 写入方式打开
* QIODevice::ReadWrite 读写方式打开
* QIODevice::Append 追加方式打开
* QIODevice::Truncate 截取方式打开
* QIODevice::Text 文本方式打开
*/
if(false == this_file_ptr.open(QIODevice::ReadOnly | QIODevice::Text))
{
std::cout << "打开失败" << std::endl;
return 0;
}
// 读取到文本中的字符串
QString string_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/this_file_ptr.readAll();
std::cout <<"读入长度: " << this_file_ptr.size() << std::endl;
std::cout << "字符串: " << string_value.toStdString() << std::endl;
this_file_ptr.close();
}
// 逐行读取文本档案
// PowerBy: www.cnblogs.com/lyshark
void read_line_file()
{
QFile this_file_ptr("d:/config.json");
if(this_file_ptr.open((QIODevice::ReadOnly | QIODevice::Text)))
{
QByteArray byte_array;
while(false == this_file_ptr.atEnd())
{
byte_array += this_file_ptr.readLine();
}
std::cout << "完整文本: " << QString(byte_array).toStdString() << std::endl;
this_file_ptr.close();
}
}
// 传入文本路径与写入内容,写入到档案
void write_string_file(QString file_path, QString string_value)
{
QFile this_file_ptr(file_path);
// 判断档案是否存在
if(false == this_file_ptr.exists())
{
return;
}
// 打开失败
if(false == this_file_ptr.open(QIODevice::ReadWrite | QIODevice::Text))
{
return;
}
//写入内容,注意需要转码,否则会报错
QByteArray write_string = string_value.toUtf8();
//写入QByteArray格式字符串
this_file_ptr.write(write_string);
this_file_ptr.close();
}
// 计算档案或目录大小
// PowerBy: www.cnblogs.com/lyshark
unsigned int GetFileSize(QString path)
{
QFileInfo info(path);
unsigned int ret = 0;
if(info.isFile())
{
ret = info.size();
}
else if(info.isDir())
{
QDir dir(path);
QFileInfoList list = dir.entryInfoList();
for(int i = 0; i < list.count(); i++)
{
if((list[i].fileName() != ".") && (list[i].fileName() != ".."))
{
ret += GetFileSize(list[i].absoluteFilePath());
}
}
}
return ret;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 读取档案
readonly_string_file("d:/config.json");
// 计算档案或目录大小
unsigned int file_size = GetFileSize("d:/xunjian");
std::cout << "获取档案或目录大小: " << file_size << std::endl;
// 覆写写入档案
QString write_file_path = "d:/test.json";
QString write_string = "hello lyshark";
write_string_file(write_file_path,write_string);
return a.exec();
}
实作决议根物件
中的单一
的键值对
,例如决议组态档中的blog,enable,status
等这些独立的栏位值.
// 读取JSON文本
// PowerBy: www.cnblogs.com/lyshark
QString readonly_string(QString file_path)
{
QFile this_file_ptr(file_path);
if(false == this_file_ptr.exists())
{
return "None";
}
if(false == this_file_ptr.open(QIODevice::ReadOnly | QIODevice::Text))
{
return "None";
}
QString string_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/this_file_ptr.readAll();
this_file_ptr.close();
return string_value;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 读取档案
QString config = readonly_string("d:/config.json");
if(config == "None")
{
return 0;
}
// 字符串格式化为JSON
QJsonParseError err_rpt;
QJsonDocument root_document = QJsonDocument::fromJson(config.toUtf8(), &err_rpt);
if(err_rpt.error != QJsonParseError::NoError)
{
std::cout << "JSON格式错误" << std::endl;
return 0;
}
// 获取到Json字符串的根节点
QJsonObject root_object = root_document.object();
// 决议blog栏位
QString blog = root_object.find("blog").value().toString();
std::cout << "栏位对应的值 = > "<< blog.toStdString() << std::endl;
// 决议enable栏位
bool enable = root_object.find("enable").value().toBool();
std::cout << "是否开启状态: " << enable << std::endl;
// 决议status栏位
int status = root_object.find("status").value().toInt();
std::cout << "状态数值: " << status << std::endl;
return a.exec();
}
实作决议简单的单物件
与单阵列
结构,如上组态档中的GetDict
与GetList
既是我们需要决议的内容.
// 读取JSON文本
QString readonly_string(QString file_path)
{
QFile this_file_ptr(file_path);
if(false == this_file_ptr.exists())
{
return "None";
}
if(false == this_file_ptr.open(QIODevice::ReadOnly | QIODevice::Text))
{
return "None";
}
QString string_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/this_file_ptr.readAll();
this_file_ptr.close();
return string_value;
}
// PowerBy: www.cnblogs.com/lyshark
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 读取档案
QString config = readonly_string("d:/config.json");
if(config == "None")
{
return 0;
}
// 字符串格式化为JSON
QJsonParseError err_rpt;
QJsonDocument root_document = QJsonDocument::fromJson(config.toUtf8(), &err_rpt);
if(err_rpt.error != QJsonParseError::NoError)
{
std::cout << "JSON格式错误" << std::endl;
return 0;
}
// 获取到Json字符串的根节点
QJsonObject root_object = root_document.object();
// 决议单一物件
// PowerBy: www.cnblogs.com/lyshark
QJsonObject get_dict_ptr = root_object.find("GetDict").value().toObject();
QVariantMap map = get_dict_ptr.toVariantMap();
if(map.contains("address") && map.contains("username") && map.contains("password") && map.contains("update"))
{
QString address = map["address"].toString();
QString username = map["username"].toString();
QString password = map["password"].toString();
QString update = map["update"].toString();
std::cout
<< " 地址: " << address.toStdString()
<< " 用户名: " << username.toStdString()
<< " 密码: " << password.toStdString()
<< " 更新日期: " << update.toStdString()
<< std::endl;
}
// 决议单一阵列
QJsonArray get_list_ptr = root_object.find("GetList").value().toArray();
for(int index=0; index < get_list_ptr.count(); index++)
{
int ref_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/get_list_ptr.at(index).toInt();
std::cout <<"输出阵列元素: " << ref_value << std::endl;
}
return a.exec();
}
实作决议物件嵌套物件
且物件中嵌套阵列
结构,如上组态档中的ObjectInArrayJson
既是我们需要决议的内容.
// 读取JSON文本
QString readonly_string(QString file_path)
{
QFile this_file_ptr(file_path);
if(false == this_file_ptr.exists())
{
return "None";
}
if(false == this_file_ptr.open(QIODevice::ReadOnly | QIODevice::Text))
{
return "None";
}
QString string_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/this_file_ptr.readAll();
this_file_ptr.close();
return string_value;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 读取档案
QString config = readonly_string("d:/config.json");
if(config == "None")
{
return 0;
}
// 字符串格式化为JSON
// PowerBy: www.cnblogs.com/lyshark
QJsonParseError err_rpt;
QJsonDocument root_document = QJsonDocument::fromJson(config.toUtf8(), &err_rpt);
if(err_rpt.error != QJsonParseError::NoError)
{
std::cout << "JSON格式错误" << std::endl;
return 0;
}
// 获取到Json字符串的根节点
QJsonObject root_object = root_document.object();
// 找到Object物件
QJsonObject one_object_json = root_object.find("ObjectInArrayJson").value().toObject();
// 转为MAP映射
QVariantMap map = one_object_json.toVariantMap();
// 寻找One键
QJsonArray array_one = map["One"].toJsonArray();
for(int index=0; index < array_one.count(); index++)
{
QString value = https://www.cnblogs.com/LyShark/archive/2022/01/06/array_one.at(index).toString();
std::cout <<"One => "<< value.toStdString() << std::endl;
}
// 寻找Two键
QJsonArray array_two = map["Two"].toJsonArray();
for(int index=0; index < array_two.count(); index++)
{
QString value = https://www.cnblogs.com/LyShark/archive/2022/01/06/array_two.at(index).toString();
std::cout <<"Two => "<< value.toStdString() << std::endl;
}
return a.exec();
}
实作决议阵列中的阵列
结构,如上组态档中的ArrayJson
既是我们需要决议的内容.
// 读取JSON文本
// PowerBy: www.cnblogs.com/lyshark
QString readonly_string(QString file_path)
{
QFile this_file_ptr(file_path);
if(false == this_file_ptr.exists())
{
return "None";
}
if(false == this_file_ptr.open(QIODevice::ReadOnly | QIODevice::Text))
{
return "None";
}
QString string_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/this_file_ptr.readAll();
this_file_ptr.close();
return string_value;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 读取档案
QString config = readonly_string("d:/config.json");
if(config == "None")
{
return 0;
}
// 字符串格式化为JSON
QJsonParseError err_rpt;
QJsonDocument root_document = QJsonDocument::fromJson(config.toUtf8(), &err_rpt);
if(err_rpt.error != QJsonParseError::NoError)
{
std::cout << "json 格式错误" << std::endl;
return 0;
}
// 获取到Json字符串的根节点
QJsonObject root_object = root_document.object();
// 获取MyJson阵列
QJsonValue array_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/root_object.value("ArrayJson");
// 验证节点是否为阵列
if(array_value.isArray())
{
// 得到阵列个数
int array_count = array_value.toArray().count();
// 回圈阵列个数
for(int index=0;index <= array_count;index++)
{
QJsonValue parset = array_value.toArray().at((index));
if(parset.isArray())
{
QString address = parset.toArray().at(0).toString();
QString username = parset.toArray().at(1).toString();
QString userport = parset.toArray().at(2).toString();
std::cout
<< "地址: " << address.toStdString()
<< " 用户名: " << username.toStdString()
<< " 埠号: " << userport.toStdString()
<< std::endl;
}
}
}
return a.exec();
}
实作决议阵列中的多物件
结构,如上组态档中的ObjectJson
既是我们需要决议的内容.
// 读取JSON文本
// PowerBy: www.cnblogs.com/lyshark
QString readonly_string(QString file_path)
{
QFile this_file_ptr(file_path);
if(false == this_file_ptr.exists())
{
return "None";
}
if(false == this_file_ptr.open(QIODevice::ReadOnly | QIODevice::Text))
{
return "None";
}
QString string_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/this_file_ptr.readAll();
this_file_ptr.close();
return string_value;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 读取档案
QString config = readonly_string("d:/config.json");
if(config == "None")
{
return 0;
}
// 字符串格式化为JSON
QJsonParseError err_rpt;
QJsonDocument root_document = QJsonDocument::fromJson(config.toUtf8(), &err_rpt);
if(err_rpt.error != QJsonParseError::NoError)
{
std::cout << "json 格式错误" << std::endl;
return 0;
}
// 获取到Json字符串的根节点
QJsonObject root_object = root_document.object();
// 获取MyJson阵列
QJsonValue object_value = https://www.cnblogs.com/LyShark/archive/2022/01/06/root_object.value("ObjectJson");
// 验证是否为阵列
// PowerBy: www.cnblogs.com/lyshark
if(object_value.isArray())
{
// 获取物件个数
int object_count = object_value.toArray().count();
// 回圈个数
for(int index=0;index <= object_count;index++)
{
QJsonObject obj = object_value.toArray().at(index).toObject();
// 验证阵列不为空
if(!obj.isEmpty())
{
QString address = obj.value("address").toString();
QString username = obj.value("username").toString();
std::cout << "地址: " << address.toStdString() << " 用户: " << username.toStdString() << std::endl;
}
}
}
return a.exec();
}
文章出处:https://www.cnblogs.com/LyShark/p/15769760.html 著作权宣告:本博客文章与代码均为学习时整理的笔记,博客中除去明确标注有参考文献的文章,其他文章 [均为原创] 作品,转载请 [添加出处] ,您添加出处是我创作的动力!
如果您恶意转载本人文章并被本人发现,则您的整站文章,将会变为我的原创作品,请相互尊重 !
0 评论