[QT] [JSON] json file read and write operations in qt

1 JSON file introduction

Identify the object in the JSON
[] array
{}
We can observe the following Json content. The goal is to read out this content and fill it into the form, and at the same time update this part of the content in the form and update this file at the same time.

[
    {
        "mode": "测试模式1",
        "module": [
            {
                "ev": "",
                "name": "",
                "wb": ""
            }
        ]
    },
    {
        "mode": "测试模式2",
        "module": [
            {
                "ev": "-21",
                "name": "模组名字1",
                "wb": "5200"
            },
            {
                "ev": "-21",
                "name": "模组名字2",
                "wb": "5200"
            }
        ]
    }
]

First observe the structure of the above Json file.
It can be seen that the corresponding outer circle large array must be constructed first.
Inserting each object in the array (recording objects with a structure)
is shown as follows:
insert image description hereSee the above figure to get a general idea of ​​how to disassemble the contents of this file for reading operations
Start defining the structure based on the above content

 //module
    struct module
    {
        QString mName;
        QString wb;
        QString ev;
    };
	//对象结构体
    struct mJson
    {
        QString mode;
        QVector<module> mModule;
        int moduleSize = 0;                                //用于module的个数
        int modeSize = 0;                                  //mode  的个数
        bool isNull = true;                                 //预留判空
    };
    mJson JsonTemp;                        			 //存储单个信息的结构体
    QVector<mJson > JsonTxt;                	//存储所有相关配置内容

2 Read the JSON file

Create a table before the read operation
We wrote a class here to inherit QTableView to display the table]

myJson::myJson() : QTableView()

Do a good job of initializing the content of the table

    model = new QStandardItemModel(this);
    // 初始化tableView表头
    model->setColumnCount(4);
    model->setHeaderData(0,Qt::Horizontal,QString("mode"));		//第一列加载mode关键字内容
    model->setHeaderData(1,Qt::Horizontal,QString("name"));		//第二列加载mode关键字内容
    model->setHeaderData(2,Qt::Horizontal,QString("wb"));		//第三列加载mode关键字内容
    model->setHeaderData(3,Qt::Horizontal,QString("ev"));		//第四列加载mode关键字内容

    setModel(model);

   //设置列宽
    setColumnWidth(0,100);
    setColumnWidth(1,150);
   	...

start reading file

//byteArr内传递JSON的数据
QJsonParseError jsonError;
QJsonDocument document = QJsonDocument::fromJson(byteArr,&jsonError);           //转化为JSON文档

if(jsonError.error!=QJsonParseError::NoError)
{
//JSON文件加载内容报错.需要提示报错信息
}
else
{
//执行解析操作
}

The detailed code of the parsing operation is as follows

        if(document.isArray())
        {
            int modeNum = document.array().size();
            //循环读取json外圈大循环mode
            for(int i = 0; i <  modeNum; ++i)
            {
                QJsonObject obj = document[i].toObject();

                QStringList keys = obj.keys();
                QJsonValue value = obj.value("mode");
                JsonTemp.mode = value.toString();

                value = obj.value("module");
                int size = value.toArray().size();                     
                JsonTemp.isNull = true;                        //必须要加避免读空而误删数据
                if(value.isArray()&&size)
                {
                    JsonTemp.isNull = false;                 	 //size不为0,则设置为非空作为标记点
                    JsonTemp.moduleSize = size;             	 //mode size置位
                    JsonTemp.mModule.clear();                	 //需要提前清空缓存数据
                    for(int i = 0 ; i < size;++i)
                    {
                        QJsonObject objModule = value[i].toObject();

                        QJsonValue nameValue            =   objModule.value("name");
                        QJsonValue wbValue              =   objModule.value("wb");
                        QJsonValue ev                   =   objModule.value("ev");
                        module moduleTemp;
                        moduleTemp.mName                = nameValue.toString();
                        moduleTemp.wb                   = wbValue.toString();
                        moduleTemp.ev                   = ev.toString();
                        JsonTemp.mModule.push_back(moduleTemp);                //需要配合clear来尾插
                        dataCount++;                                                    //记录有效数据个数
                    }
                }
                JsonTxt.push_back(JsonTemp);
            }
        }

So far, all the content of the file has been read and stored in
JsonTxt.
The next thing to do is to add the content to the table.
The structure I wrote records the number of valid data and empty data positions.
So just fill the form directly according to the total amount of data.

        int size = JsonTxt.size();
        int cur = 0;
        int dateNum = 0;                                        //用于记录表格中的数据个数
        for(int i = 0 ; i < size ;++i)
        {
            if(JsonTxt[i].isNull)
            {
                model->setItem(i,0,new QStandardItem(JsonTxt[i].mode));
                ++cur;   //空数据的偏移用于指向当前数据的位置。
                ++dateNum;
            }
            else
            {
                while (cur < size)
                {
                    int groupSize = JsonTxt[cur].module_size;
                    for(int i = 0 ;i < groupSize;++i)
                    {
                        model->setItem(dateNum,0,new QStandardItem(JsonTxt[cur].mode));
                        model->setItem(dateNum,1,new QStandardItem(JsonTxt[cur].mModule[i].mName));
                        model->setItem(dateNum,2,new QStandardItem(JsonTxt[cur].mModule[i].wb));
                        model->setItem(dateNum,3,new QStandardItem(JsonTxt[cur].mModule[i].ev));
                        ++dateNum;
                    }
                    ++cur;
                }
            }
        }

At this point, the table can already see the corresponding table data
insert image description here

3 Write JSON file

The essence and parsing of writing JSON files are reversed.
Conceive the content in the Json file first

    QJsonArray jsonArrayALL;
    QJsonObject jsonObjectALL;

    QJsonArray jsonArrayModule[JsonTxt.size()];
    QJsonObject jsonObjectModule;

    QJsonDocument jsonDoc;
    QString mode;
    QString mode_last;

    int tempModeCount = 0;
    for(int i = 0; i < row;++i)	//扫描行
    {
        for(int j = 0;j < column;++j)			//扫描列
        {
            module TabData;
            switch(j)
            {
                case 0:
                    mode = model->index(i,j).data().toString();
                    break;
                case 1:   
                    TabData.mName = model->index(i,j).data().toString();
                    jsonObjectModule.insert("name",TabData.mName);
                    break;
                case 2:  
                    TabData.wb = model->index(i,j).data().toString();
                    jsonObjectModule.insert("wb",TabData.wb);
                    break;
                case 3:  
                    TabData.ev = model->index(i,j).data().toString();
                    jsonObjectModule.insert("ev",TabData.ev);
                    break;
            }
        }
		//去重复操作
        if (mode_last.toStdString() != mode.toStdString())
        {
            ++tempModeCount;
        }

        jsonArrayModule[tempModeCount-1].push_back(jsonObjectModule);

        mode_last = mode;
    }
    int mode_size = JsonTxt.size();

    for(int i = 0;i < mode_size;++i)
    {
        mode = JsonTxt.at(i).mode;
        jsonObjectALL.insert("mode",mode);
        jsonObjectALL.insert("module",jsonArrayModule[i]);
        jsonArrayALL.push_back(jsonObjectALL);
    }

    jsonDoc.setArray(jsonArrayALL);
    QByteArray json = jsonDoc.toJson();

	//写文件
    QFile file("输出.json");
    file.open(QIODevice::WriteOnly);
    file.write(json);
    file.close();

So far, the reading and writing of the json file in Qt has been completed.

おすすめ

転載: blog.csdn.net/qq_38753749/article/details/128885457