Qt 之 自定义json配置文件类,QJsonDocument应用

目录

一、前言

二、头文件代码

三、源文件代码

四、使用示例

五、使用效果


一、前言

        Qt的配置类QSettings主要是键值结构的配置,若需要的配置项为树形结构,例如配置学校\学院\班级\学生这样,使用键值结构已经不满足我们的需求了,我们可以使用xml文件或json文件实现树形结构的配置。本文实现自定义的json文件配置类,实现快速的对json文件的增删改查。

        本代码示例对学院\班级\课程的配置,配置的结构有变化可自行修改代码,对json文件的增删改查结构可以通用。

二、头文件代码

jsonConfig.h
#pragma once

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

//班级
struct mClass{
    QString ClassName = "";            //班级名
    QVector CourseName ={};   //课程列表
};
//学院
struct mFaculty {
    QString FacultyName = "";    //学院名
    QVector Class = {};  //班级列表
};


class jsonConfig  : public QObject
{
	Q_OBJECT

public:
	~jsonConfig();
	jsonConfig& operator = (const jsonConfig&) = delete;
	static jsonConfig& getInstance(void);

    QJsonObject mStruct2JsonObject(mFaculty);
    mFaculty jsonObject2MStruct(QJsonObject);

    bool find(QString name, mFaculty* out_mStruct = NULL);
    void add(mFaculty);
    void modify(mFaculty);
    void remove(QString facultyName);
    QVector readAll();

private:
	jsonConfig();
	static jsonConfig* instance;

	QFile *jsonFile;
};

三、源文件代码

jsonConfig.cpp
#include "jsonConfig.h"

jsonConfig* jsonConfig::instance = NULL;

jsonConfig::jsonConfig()
{
    QDir* dir = new QDir();
    if (!dir->exists("./config"))
        dir->mkpath("./config");
    jsonFile = new QFile("./config/jsonConfigFile.json");
    if (!jsonFile->exists()) {
        if (jsonFile->open(QFile::WriteOnly)) {
            QJsonObject obj;
            QJsonArray arr;
            obj.insert("Faculty", arr);
            QJsonDocument doc(obj);
            QByteArray data = doc.toJson();
            jsonFile->write(data);
            jsonFile->close();
        }
    }
}

jsonConfig::~jsonConfig()
{}

jsonConfig& jsonConfig::getInstance(void)
{
    if (instance == NULL)
        instance = new jsonConfig();
    return *instance;
}

bool jsonConfig::find(QString name, mFaculty* out_mStruct)
{
    if (!jsonFile->open(QIODevice::ReadOnly))
        return false;
    QByteArray data = jsonFile->readAll();
    jsonFile->close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return false;
    }
    QJsonObject rootObj = doc.object();
    if (rootObj.contains("Faculty")) {
        if (rootObj.value("Faculty").type() == QJsonValue::Array) {
            QJsonArray sceneArray = rootObj.value("Faculty").toArray();
            for (int i = 0; i < sceneArray.size(); i++) {
                if (sceneArray.at(i).type() == QJsonValue::Object) {
                    QJsonObject obj = sceneArray.at(i).toObject();
                    if (obj.value("facultyName").toString() == name) {
                        *out_mStruct = jsonObject2MStruct(obj);
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

QJsonObject jsonConfig::mStruct2JsonObject(mFaculty faculty)
{
    QJsonObject obj;
    obj.insert("facultyName", faculty.FacultyName);
    QJsonArray classArray;
    for (int i = 0; i < faculty.Class.size(); i++){
        QJsonObject classObj;
        classObj.insert("className", faculty.Class.at(i).ClassName);
        QJsonArray courseArray;
        for(QString course : faculty.Class.at(i).CourseName){
            if(!course.isEmpty())
                courseArray.append(course);
        }
        classObj.insert("classCourses",courseArray);
        classArray.append(classObj);
    }
    obj.insert("class", classArray);
    return obj;

}

mFaculty jsonConfig::jsonObject2MStruct(QJsonObject jsonObject)
{
    mFaculty faculty;
    if (jsonObject.value("facultyName").type() == QJsonValue::String)
        faculty.FacultyName = jsonObject.value("facultyName").toString();
    if (jsonObject.value("class").type() == QJsonValue::Array) {
        QJsonArray classArray = jsonObject.value("class").toArray();
        for (int i = 0; i < classArray.size(); i++) {
            mClass Class;
            QJsonObject classObj = classArray.at(i).toObject();
            if(classObj.value("className").type() == QJsonValue::String)
                Class.ClassName = classObj.value("className").toString();
            if(classObj.value("classCourses").type() == QJsonValue::Array){
                QJsonArray courseArray = classObj.value("classCourses").toArray();
                for (int j = 0; j < courseArray.size(); j++) {
                    if(!courseArray.at(j).toString().isEmpty())
                        Class.CourseName.append(courseArray.at(j).toString());
                }
            }
            faculty.Class.append(Class);
        }
    }
    return faculty;
}

void jsonConfig::add(mFaculty faculty)
{
    QJsonObject addObj = mStruct2JsonObject(faculty);
    if (!jsonFile->open(QIODevice::ReadOnly))
        return;
    QByteArray data = jsonFile->readAll();
    jsonFile->close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return;
    }
    QJsonObject rootObj = doc.object();

    if (rootObj.contains("Faculty")) {
        if (rootObj.value("Faculty").type() == QJsonValue::Array) {
            QJsonArray sceneArray = rootObj.value("Faculty").toArray();
            sceneArray.append(addObj);
            rootObj["Faculty"] = sceneArray;
        }
    }
    
    doc.setObject(rootObj);
    if (!jsonFile->open(QFile::WriteOnly | QFile::Truncate))
        return;
    QByteArray writeData = doc.toJson();
    jsonFile->write(writeData);
    jsonFile->close();
}

void jsonConfig::modify(mFaculty faculty)
{
    QJsonObject modifyObj = mStruct2JsonObject(faculty);
    if (!jsonFile->open(QIODevice::ReadOnly))
        return;
    QByteArray data = jsonFile->readAll();
    jsonFile->close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return;
    }
    QJsonObject rootObj = doc.object();

    if (rootObj.contains("Faculty")) {
        if (rootObj.value("Faculty").type() == QJsonValue::Array) {
            QJsonArray facultyArray = rootObj.value("Faculty").toArray();
            for (int i = 0; i < facultyArray.size(); i++) {
                if (facultyArray.at(i).type() == QJsonValue::Object) {
                    QJsonObject obj = facultyArray.at(i).toObject();
                    if (obj.value("facultyName").toString() == modifyObj.value("facultyName").toString()) {
                        facultyArray.removeAt(i);
                        facultyArray.append(modifyObj);
                    }
                }
            }
            rootObj["Faculty"] = facultyArray;
        }
    }

    doc.setObject(rootObj);
    if (!jsonFile->open(QFile::WriteOnly | QFile::Truncate))
        return;
    QByteArray writeData = doc.toJson();
    jsonFile->write(writeData);
    jsonFile->close();
}

void jsonConfig::remove(QString facultyName)
{
    if (!jsonFile->open(QIODevice::ReadOnly))
        return;
    QByteArray data = jsonFile->readAll();
    jsonFile->close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return;
    }
    QJsonObject rootObj = doc.object();

    if (rootObj.contains("Faculty")) {
        if (rootObj.value("Faculty").type() == QJsonValue::Array) {
            QJsonArray sceneArray = rootObj.value("Faculty").toArray();
            for (int i = 0; i < sceneArray.size(); i++) {
                if (sceneArray.at(i).type() == QJsonValue::Object) {
                    QJsonObject obj = sceneArray.at(i).toObject();
                    if (obj.value("facultyName").toString() == facultyName)
                        sceneArray.removeAt(i);
                }
            }
            rootObj["Faculty"] = sceneArray;
        }
    }

    doc.setObject(rootObj);
    if (!jsonFile->open(QFile::WriteOnly | QFile::Truncate))
        return;
    QByteArray writeData = doc.toJson();
    jsonFile->write(writeData);
    jsonFile->close();
}

QVector jsonConfig::readAll()
{
    QVector faculty;
    if (!jsonFile->open(QIODevice::ReadOnly))
        return faculty;
    QByteArray data = jsonFile->readAll();
    jsonFile->close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return faculty;
    }
    QJsonObject rootObj = doc.object();
    if (rootObj.contains("Faculty")) {
        if (rootObj.value("Faculty").type() == QJsonValue::Array) {
            QJsonArray facultyArray = rootObj.value("Faculty").toArray();
            for (int i = 0; i < facultyArray.size(); i++) {
                if (facultyArray.at(i).type() == QJsonValue::Object) {
                    QJsonObject obj = facultyArray.at(i).toObject();
                    mFaculty scene = jsonObject2MStruct(obj);
                    faculty.push_back(scene);
                }
            }
        }
    }
    return faculty;
}

四、使用示例

#include "jsonConfig.h"

int main(int argc, char *argv[])
{
    //添加到配置文件
    mFaculty faculty;
    faculty.FacultyName = "数学学院";
    jsonConfig::getInstance().add(faculty);

    //从配置文件删除
    jsonConfig::getInstance().remove("美术学院");

    //查找并修改配置
    mFaculty findFaculty;
    jsonConfig::getInstance().find("音乐学院",&findFaculty);
    for(int i = 0; i  facultys = jsonConfig::getInstance().readAll();

}

五、使用效果

Qt 之 自定义json配置文件类,QJsonDocument应用_第1张图片

 使用后添加内容后,在文件夹下生成jsonConfigFile.json文件。

你可能感兴趣的:(Qt进阶之路,json,qt,c++)