当前位置:网站首页>[QT] QT uses qjson to generate JSON files and save them

[QT] QT uses qjson to generate JSON files and save them

2022-07-05 23:58:00 Cappuccino-jay

Sample 1:

#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QJsonObject>
#include <QDebug>
#include <QJsonArray>
#include <QByteArray>
 
void createJson()
{
    
	QVariantHash data;
 
	QVariantHash subData1;
	subData1.insert("name", "apple");
	subData1.insert("icon", "appleIcon");
	subData1.insert("describe", "an apple");
 
	data.insert("first fruit", subData1);
 
	QVariantHash subData2;
	subData2.insert("name", "orange");
	subData2.insert("icon", "orangeIcon");
	subData2.insert("describe", "an orange");
	data.insert("second fruit", subData2);
 
	QJsonArray array1;
	for (int i = 0; i < 5; i++)
	{
    
		array1.insert(i, QString::fromLocal8Bit("eat %1").arg(i));
	}
 
	data.insert("three fruit array", array1);
 
	QJsonObject rootObj = QJsonObject::fromVariantHash(data);
	QJsonDocument document;
	document.setObject(rootObj);
 
	QByteArray byte_array = document.toJson(QJsonDocument::Compact);
	QString json_str(byte_array);
	// Fill in the path according to the actual 
	QFile file("D:\\1.json");
 
	if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
	{
    
		qDebug() << "file error!";
	}
	QTextStream in(&file);
	in << json_str;
 
	file.close();   //  close file
}

Sample 2:

Create a new one QT Empty item :

#include <QCoreApplication>

#include <QJsonObject> // { }
#include <QJsonArray> // [ ]
#include <QJsonDocument> //  analysis Json
#include <QJsonValue> // int float double bool null { } [ ]
#include <QJsonParseError>

#include <QDebug>
#include <QFile>
#include <QTextStream>

#pragma execution_character_set("utf-8") // qt Support to display Chinese 

//  encapsulation Json
void createJson() {
    
    /* * "interest": { * "basketball": " Basketball ", * "badminton": " badminton " * }, */
    //  Definition  { }  object 
    QJsonObject interestObj;
    //  Insert elements , Corresponding key value pairs 
    interestObj.insert("basketball", " Basketball ");
    interestObj.insert("badminton", " badminton ");

    /* * "color": [ "black", "white"], */
    //  Definition  [ ]  Array 
    QJsonArray colorArray;
    //  Add elements to the array 
    colorArray.append("black");
    colorArray.append("white");

    /* * "like": [ * { "game": " War Within Three Kingdoms ", "price": 58.5 }, * { "game": " Island soldiers ", "price": 66.65 } * ], */
    //  Definition  { }  object 
    QJsonObject likeObject1;
    likeObject1.insert("game", " War Within Three Kingdoms ");
    likeObject1.insert("price", 58.5);
    
    QJsonObject likeObject2;
    likeObject2.insert("game", " Island soldiers ");
    likeObject2.insert("price", 66.65);

    //  Definition  [ ]  object 
    QJsonArray likeArray;
    likeArray.append(likeObject1);
    likeArray.append(likeObject2);

    /* * "languages": { * "serialOne": { "language": " chinese ", "grade": 10 }, * "serialTwo": { "language": " English ", "grade": 6 } * }, */
    //  Definition  { }  object 
    QJsonObject language1;
    language1.insert("language", " chinese ");
    language1.insert("grade", 10);

    QJsonObject language2;
    language2.insert("language", " English ");
    language2.insert("grade", 6);

    QJsonObject languages;
    //  take { }  Insert  { }  in 
    languages.insert("serialOne", language1);
    languages.insert("serialTwo", language2);

    //  Define the root node   That is, the outermost layer  { }
    QJsonObject rootObject;

    //  Insert elements 
    rootObject.insert("name", " Lao Wang ");
    rootObject.insert("age", 26);
    rootObject.insert("interest", interestObj);
    rootObject.insert("color", colorArray);
    rootObject.insert("like", likeArray);
    rootObject.insert("languages", languages);
    rootObject.insert("vip", true);
    rootObject.insert("address", QJsonValue::Null);

    //  take json The data in the object is converted into a string 
    QJsonDocument doc;
    //  take object Set as the main object of this document 
    doc.setObject(rootObject);

    // Json Save the string to json In the document 
    QFile file("../Json/js.json");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
    
        qDebug() << "can't open error!";
        return;
    }

    QTextStream stream(&file);
    stream.setCodec("UTF-8");		//  Set the write encoding to UTF8
    //  write file 
    stream << doc.toJson();
    file.close();
}

//  analysis Json
void analysisJson() {
    
    QFile file("../Json/js.json");
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
    
        qDebug() << "can't open error!";
        return;
    }

    //  Read the entire contents of the file 
    QTextStream stream(&file);
    stream.setCodec("UTF-8");		//  Set the read code to UTF8
    QString str = stream.readAll();

    file.close();

    /*  analysis Json */

    // QJsonParseError Class is used in JSON Error reported during parsing .
    QJsonParseError jsonError;
    //  take json It can be interpreted as UTF-8 Coded json file , And create a QJsonDocument.
    //  If the parsing is successful , return QJsonDocument object , Otherwise return to null
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(), &jsonError);
    //  Judge whether the parsing fails 
    if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
    
        qDebug() << "Json Format error !" << jsonError.error;
        return;
    }

    //  Get root  { }
    QJsonObject rootObj = doc.object();

    //  Get value from key 
    QJsonValue nameValue = rootObj.value("name");
    qDebug() << "name = " << nameValue.toString();

    QJsonValue ageValue = rootObj.value("age");
    qDebug() << "age = " << ageValue.toInt();

    //  Parse object  { }
    QJsonValue interestValue = rootObj.value("interest");
    //  Judge whether it is object type 
    if (interestValue.type() == QJsonValue::Object) {
    
        //  Convert to QJsonObject type 
        QJsonObject interestObj = interestValue.toObject();

        QJsonValue basketballValue = interestObj.value("basketball");
        qDebug() << "basketball = " << basketballValue.toString();
        QJsonValue badmintonValue = interestObj.value("badminton");
        qDebug() << "badminton = " << badmintonValue.toString();
    }

    //  Parsing arrays  [ ]
    QJsonValue colorValue = rootObj.value("color");
    //  Judge whether it is Array type 
    if (colorValue.type() == QJsonValue::Array) {
    
        //  Convert to QJsonArray type 
        QJsonArray colorArray = colorValue.toArray();

        for (int i = 0; i < colorArray.size(); i++) {
    
            QJsonValue color = colorArray.at(i);
            qDebug() << "color = " << color.toString();
        }
    }

    //  Parse the objects in the array  [ { } ]
    QJsonValue likeValue = rootObj.value("like");
    if (likeValue.type() == QJsonValue::Array) {
    
        QJsonArray likeArray = likeValue.toArray();

        for (int i = 0; i < likeArray.count(); i++) {
    
            QJsonValue likeValueChild = likeArray.at(i);

            if (likeValueChild.type() == QJsonValue::Object) {
    
                QJsonObject likeObj = likeValueChild.toObject();

                QJsonValue gameLikeValue = likeObj.value("game");
                qDebug() << "game = " << gameLikeValue.toString();
                QJsonValue priceLikeValue = likeObj.value("price");
                qDebug() << "price = " << priceLikeValue.toDouble();
            }
        }
    }

    //  analysis   object   in   object  { { } }
    QJsonValue languagesValue = rootObj.value("languages");
    if (languagesValue.type() == QJsonValue::Object) {
    
        QJsonObject languagesObj = languagesValue.toObject();

        QJsonValue serialOneValue = languagesObj.value("serialOne");
        if (serialOneValue.type() == QJsonValue::Object) {
    
            QJsonObject serialOneObj = serialOneValue.toObject();

            QJsonValue languageValue = serialOneObj.value("language");
            qDebug() << "language = " << languageValue.toString();
            QJsonValue gradeValue = serialOneObj.value("grade");
            qDebug() << "grade = " << gradeValue.toInt();
        }

        QJsonValue serialTwoValue = languagesObj.value("serialTwo");
        if (serialTwoValue.type() == QJsonValue::Object) {
    
            QJsonObject serialTwoObj = serialTwoValue.toObject();

            QJsonValue languageValue = serialTwoObj.value("language");
            qDebug() << "language = " << languageValue.toString();
            QJsonValue gradeValue = serialTwoObj.value("grade");
            qDebug() << "grade = " << gradeValue.toInt();
        }
    }

    //  analysis  bool type 
    QJsonValue vipValue = rootObj.value("vip");
    qDebug() << "vip = " << vipValue.toBool();


    //  analysis  null type 
    QJsonValue addressValue = rootObj.value("address");
    if (addressValue.type() == QJsonValue::Null) {
    
        qDebug() << "address = " << "null";
    }

}

//  modify Json data 
void alterJson() {
    
    /*  If you want to modify it, just rewrite it again and overwrite it  */

    QFile readFile("../Json/js.json");
    if (!readFile.open(QFile::ReadOnly | QFile::Truncate)) {
    
        qDebug() << "can't open error!";
        return;
    }

    //  Read the entire contents of the file 
    QTextStream readStream(&readFile);
    readStream.setCodec("UTF-8");		//  Set the read code to UTF8
    QString str = readStream.readAll();
    readFile.close();

    /*  modify Json */

    // QJsonParseError Class is used in JSON Error reported during parsing .
    QJsonParseError jsonError;
    //  take json It can be interpreted as UTF-8 Coded json file , And create a QJsonDocument.
    //  If the parsing is successful , return QJsonDocument object , Otherwise return to null
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
    
        qDebug() << "Json Format error !" << jsonError.error;
        return;
    }

    //  Get root  { }
    QJsonObject rootObj = doc.object();

    //  modify name attribute 
    rootObj["name"] = " Lao Li ";
    rootObj["vip"] = false;


    //  Modify array [] The elements in 
    QJsonValue colorValue = rootObj.value("color");
    if (colorValue.type() == QJsonValue::Array) {
    
        QJsonArray colorArray = colorValue.toArray();

        //  Modify the values in the array 
        colorArray.replace(0, "blue");
        colorArray.replace(1, "green");

        //  Assignment overrides the original array attribute 
        rootObj["color"] = colorArray;
    }

    //  modify  { }  The value in 
    QJsonValue interestValue = rootObj.value("interest");
    if (interestValue.type() == QJsonValue::Object) {
    
        QJsonObject interestObject = interestValue.toObject();

        interestObject["badminton"] = " Table Tennis ";
        interestObject["basketball"] = " football ";

        rootObj["interest"] = interestObject;
    }


    //  modify  { { } }  The value in 
    QJsonValue languagesValue = rootObj.value("languages");
    if (languagesValue.type() == QJsonValue::Object) {
    
        QJsonObject languagesObj = languagesValue.toObject();

        //  Find the first one inside  { }
        QJsonValue serialOneValue = languagesObj.value("serialOne");
        if (serialOneValue.type() == QJsonValue::Object) {
    
            QJsonObject serialOneObj = serialOneValue.toObject();

            serialOneObj["grade"] = "20";

            languagesObj["serialOne"] = serialOneObj;
        }

        //  Find the second inside  { }
        QJsonValue serialTwoValue = languagesObj.value("serialTwo");
        if (serialTwoValue.type() == QJsonValue::Object) {
    
            QJsonObject serialTwoObj = serialTwoValue.toObject();

            serialTwoObj["grade"] = "10";
            serialTwoObj["language"] = " Cantonese ";

            languagesObj["serialTwo"] = serialTwoObj;
        }

        rootObj["languages"] = languagesObj;
    }

    //  modify  [ { } ]
    QJsonValue likeValue = rootObj.value("like");
    if (likeValue.type() == QJsonValue::Array) {
    
        QJsonArray likeArray = likeValue.toArray();

        //  Get the corresponding according to the index { }
        QJsonObject obj1 = likeArray[0].toObject();
        obj1["game"] = " Happy game ";
        obj1["price"] = 88.8;
        QJsonObject obj2 = likeArray[1].toObject();
        obj2["game"] = " Happy bullfight ";
        obj2["price"] = 77.7;

        //  Replace overlay 
        likeArray.replace(0, obj1);
        likeArray.replace(1, obj2);

        rootObj["like"] = likeArray;
    }

    //  take object Set as the main object of this document 
    doc.setObject(rootObj);

    //  Rewrite open file , Overwrite the original file , Achieve the effect of deleting all the contents of the file 
    QFile writeFile("../Json/js.json");
    if (!writeFile.open(QFile::WriteOnly | QFile::Truncate)) {
    
        qDebug() << "can't open error!";
        return;
    }

    //  Write the modified content to the file 
    QTextStream wirteStream(&writeFile);
    wirteStream.setCodec("UTF-8");		//  Set the read code to UTF8
    wirteStream << doc.toJson();		//  write file 
    writeFile.close();					//  Close file 
}

//  Delete Json
void delJson() {
    
    QFile readFile("../Json/js.json");
    if (!readFile.open(QFile::ReadOnly | QFile::Truncate)) {
    
        qDebug() << "can't open error!";
        return;
    }

    //  Read the entire contents of the file 
    QTextStream readStream(&readFile);
    readStream.setCodec("UTF-8");		//  Set the read code to UTF8
    QString str = readStream.readAll();
    readFile.close();

    /*  modify Json */

    // QJsonParseError Class is used in JSON Error reported during parsing .
    QJsonParseError jsonError;
    //  take json It can be interpreted as UTF-8 Coded json file , And create a QJsonDocument.
    //  If the parsing is successful , return QJsonDocument object , Otherwise return to null
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
    
        qDebug() << "Json Format error !" << jsonError.error;
        return;
    }

    //  Get root  { }
    QJsonObject rootObj = doc.object();


    //  Delete age
    rootObj.remove("age");


    //  Delete array [] The elements in 
    QJsonValue colorValue = rootObj.value("color");
    if (colorValue.type() == QJsonValue::Array) {
    
        QJsonArray colorArray = colorValue.toArray();

        //  Delete the array with index 1 Value 
        colorArray.removeAt(1);

        //  Assignment overrides the original array attribute 
        rootObj["color"] = colorArray;
    }

    //  Delete  { }  The value in 
    QJsonValue interestValue = rootObj.value("interest");
    if (interestValue.type() == QJsonValue::Object) {
    
        QJsonObject interestObject = interestValue.toObject();

        //  The delete key is basketball Attribute element of 
        interestObject.remove("basketball");

        rootObj["interest"] = interestObject;
    }
    
    //  Delete  { { } }  The value in 
    QJsonValue languagesValue = rootObj.value("languages");
    if (languagesValue.type() == QJsonValue::Object) {
    
        QJsonObject languagesObj = languagesValue.toObject();

        //  The delete key is serialTwo The object of  { }
        languagesObj.remove("serialTwo");

        rootObj["languages"] = languagesObj;
    }

    //  Delete  [ ]  Medium  { }
    QJsonValue likeValue = rootObj.value("like");
    if (likeValue.type() == QJsonValue::Array) {
    
        QJsonArray likeArray = likeValue.toArray();

        //  Delete index as 1 The values in the array 
        likeArray.removeAt(1);

        rootObj["like"] = likeArray;
    }

    //  Delete  [ ]
    rootObj.remove("color");

    //  Delete  { }
    rootObj.remove("interest");

    //  take object Set as the main object of this document 
    doc.setObject(rootObj);

    //  Rewrite open file , Overwrite the original file , Achieve the effect of deleting all the contents of the file 
    QFile writeFile("../Json/js.json");
    if (!writeFile.open(QFile::WriteOnly | QFile::Truncate)) {
    
        qDebug() << "can't open error!";
        return;
    }

    //  Write the modified content to the file 
    QTextStream wirteStream(&writeFile);
    wirteStream.setCodec("UTF-8");		//  Set the read code to UTF8
    wirteStream << doc.toJson();		//  write file 
    writeFile.close();					//  Close file 
}

int main(int argc, char *argv[]) {
    
    QCoreApplication a(argc, argv);

    createJson();

    analysisJson();

    alterJson();

    delJson();

    return a.exec();
}

remarks : Specified encoding #pragma execution_character_set(“utf-8”) // qt Support to display Chinese

Sample 3:( One json Object contains multiple arrays )

1、cjsonio.h

#ifndef CJSONIO_H
#define CJSONIO_H

#include <QHash>

class CJsonIO
{
    

public:
    CJsonIO();
    ~CJsonIO();

    static  CJsonIO * GetInstance();
    bool ReadJson(const QString& dir, const QString& fileName);
    bool WriteJson(const QString& dir, const QString& fileName);
    void PrintCurJson();
    void Init();    
    QStringList GetValue(QString key);
    
private:
    static CJsonIO m_jsonIO;
    QHash<QString, QStringList> m_hash;         // Store the current json
    QHash<QString, QStringList> m_defaultHash;      // Store default json
};

#endif // CJSONIO_H

2、cjsonio.cpp

#include "cjsonio.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonArray>
#include <QFile>
#include <QDebug>

CJsonIO CJsonIO::m_jsonIO;

CJsonIO::CJsonIO() :
   m_hash(),m_defaultHash()
{
    
    this->Init();
}

CJsonIO::~CJsonIO()
{
    

}

CJsonIO *CJsonIO::GetInstance()
{
    
    return &m_jsonIO;
}

bool CJsonIO::ReadJson(const QString &dir, const QString &fileName)
{
    
    bool result = false;
        do
        {
    
            //read document
            QString file = dir + fileName;
            QFile loadFile(file);
            if (!loadFile.open(QIODevice::ReadOnly))
            {
    
                qDebug() << "could't open projects json";
                break;
            }

            QByteArray allData = loadFile.readAll();
            loadFile.close();

            //set QJsonDocument
            QJsonParseError jsonError;
            QJsonDocument document = QJsonDocument::fromJson(allData, &jsonError); // Function description : analysis UTF-8 Coded JSON Document and create QJsonDocument.

            if (document.isNull() || (jsonError.error != QJsonParseError::NoError))
            {
    
                qDebug() << "document error";
                break;
            }
            if (jsonError.error == QJsonParseError::IllegalUTF8String)                  // Illegal in input UTF8 Sequence 
            {
    
                qDebug() << "An illegal UTF8 sequence occurred in the input";
                break;
            }

            if (!document.isObject())
            {
    
                qDebug() << "document is not object";
                break;
            }

            //read QJson
            QHash<QString, QStringList> indexHash;
            QStringList indexList;

            QStringList keys = document.object().keys();
            QJsonObject object = document.object();
            int keySize = keys.size();

            for (int i = 0; i < keySize; ++i)
            {
    
                QString strKey = keys.at(i);
                indexList.clear();

                if (object.contains(strKey))
                {
    
                    QJsonValue value = object.value(strKey);
                    if (value.isArray())
                    {
    
                        QJsonArray array = value.toArray();
                        int arrSize = array.size();
                        for (int i = 0; i < arrSize; ++i)
                        {
    
                            QJsonValue  arrValue = array.at(i);
                            if (arrValue.isString())
                            {
    
                                QString  strValue = arrValue.toString();
                                indexList.push_back(strValue);
                            }

                        }

                    }

                    indexHash.insert(strKey, indexList);
                }


            }

            this->m_hash = indexHash;
            this->m_defaultHash = indexHash;
            result = true;

        }while(false);

    return result;
}

bool CJsonIO::WriteJson(const QString &dir, const QString &fileName)
{
    
    bool result = false;
        do
        {
    
            //set QJson
            QJsonObject jsonObject;
            QHash<QString,QStringList>::const_iterator iter = this->m_hash.constBegin();
            while (iter != this->m_hash.constEnd())
            {
    
                QJsonArray jsonArray;
                QString key = iter.key();
                QStringList valueList = iter.value();

                QStringList::const_iterator listIter = valueList.begin();
                while (listIter != valueList.end())
                {
    
                    jsonArray.append(*listIter);
                    ++listIter;
                }

                jsonObject.insert(key, QJsonValue(jsonArray));
                ++iter;
            }

            //set QJsonDocument
            QJsonDocument doc(jsonObject);
            QByteArray byteArray = doc.toJson();

            //write document
            QString strFile = dir + fileName;
            QFile loadFile(strFile);
            if (!loadFile.open(QIODevice::WriteOnly))
            {
    
                qDebug() << "could't open projects json";
                break;
            }

            loadFile.write(byteArray);
            loadFile.close();

            result = true;

        }while(false);

    return result;

}

void CJsonIO::PrintCurJson()
{
    
    QHash<QString,QStringList>::const_iterator iter = this->m_hash.constBegin();
        while (iter != this->m_hash.constEnd())
        {
    
            QString key = iter.key();
            QStringList valueList = iter.value();

            qDebug() << "key:" << key << ": ";

            QStringList::const_iterator listIter = valueList.begin();
            while (listIter != valueList.end())
            {
    
                qDebug() << "value:" << *listIter;
                ++listIter;
            }
            ++iter;
        }

}

QStringList CJsonIO::GetValue(QString key)
{
    
    QStringList valueList;
    QHash<QString, QStringList>::const_iterator iter = this->m_hash.constBegin();
        while (iter != this->m_hash.constEnd())
        {
    
            QString hashKey = iter.key();
            if (hashKey == key)
            {
    
                valueList = iter.value();
            }

            ++iter;
        }

        return valueList;
}

void CJsonIO::Init()
{
    
    this->ReadJson("../Json/","read.json");
}

3、main.cpp

#include "cjsonio.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    
    QApplication a(argc, argv);
    CJsonIO *json = CJsonIO::GetInstance();
    QString dir = "../Json/";
    QString readFile = "read.json";
    QString writeFile = "write.json";

    json->ReadJson(dir, readFile);
    json->WriteJson(dir, writeFile);
    json->PrintCurJson();

    return a.exec();
}

Sample 4:

JSON encapsulation : It includes JSON The read 、 analysis 、 Generate and save these basic functions

1、json.h file

#ifndef JSON_H
#define JSON_H

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

class JSON {
    
public:
    JSON();

    QJsonObject getJson();
    QJsonObject loadJson(const QString& filepath);
    void writeJson(const QString key, bool value);
    void writeJson(const QString key, int value);
    void writeJson(const QString key, double value);
    void writeJson(const QString key, QString value);
    void writeJson(const QString key, bool* array, int length);
    void writeJson(const QString key, int* array, int length);
    void writeJson(const QString key, double* array, int length);
    void writeJson(const QString key, QJsonObject object);
    bool saveJson(const QString& filepath);
    QString toString();

private:
    QJsonObject json;
};

#endif // JSON_H

2、json.cpp file

#include <QDebug>
#include <QFile>
#include <QIODevice>

#include "json.h"

JSON::JSON()
{
    
}

QJsonObject JSON::getJson()
{
    
    return json;
}

QJsonObject JSON::loadJson(const QString& filepath)
{
    
    QFile loadFile(filepath);

    if (!loadFile.open(QIODevice::ReadOnly))
        qDebug() << "Unable to load JSON file";

    QByteArray allData = loadFile.readAll();
    loadFile.close();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &json_error));

    if (json_error.error != QJsonParseError::NoError)
        qDebug() << "JSON error!";

    QJsonObject rootObj = jsonDoc.object();
    return rootObj;
}

// NOTE: implicit conversion turns string literal into bool
void JSON::writeJson(const QString key, bool value)
{
    
    json.insert(key, value);
}

void JSON::writeJson(const QString key, int value)
{
    
    json.insert(key, value);
}

void JSON::writeJson(const QString key, double value)
{
    
    json.insert(key, value);
}

// value only support QString
void JSON::writeJson(const QString key, QString value)
{
    
    json.insert(key, QString(value));
}

void JSON::writeJson(const QString key, bool* array, int length)
{
    
    QJsonArray arr;
    for (int i = 0; i < length; i++)
        arr.append(array[i]);
    json.insert(key, arr);
}

void JSON::writeJson(const QString key, int* array, int length)
{
    
    QJsonArray arr;
    for (int i = 0; i < length; i++)
        arr.append(array[i]);
    json.insert(key, arr);
}

void JSON::writeJson(const QString key, double* array, int length)
{
    
    QJsonArray arr;
    for (int i = 0; i < length; i++)
        arr.append(array[i]);
    json.insert(key, arr);
}

void JSON::writeJson(const QString key, QJsonObject object)
{
    
    json.insert(key, object);
}

bool JSON::saveJson(const QString& filepath)
{
    
    QJsonDocument document;
    document.setObject(json);
    QFile file(filepath);

    if (!file.open(QIODevice::WriteOnly)) {
    
        qDebug() << "Fail to save contents to JSON file";
        return false;
    }

    file.write(document.toJson());

    return true;
}

QString JSON::toString()
{
    
    QJsonDocument document;
    document.setObject(json);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString str(byteArray);
    return str;
}

3、main.cpp file ( The test data )

#include <QApplication>
#include <QDebug>
#include <QHBoxLayout>
#include <QLabel>

#include "json.h"
#include "mainwindow.h"

int main(int argc, char* argv[])
{
    
    QApplication a(argc, argv);
    MainWindow w;

    int arr[] = {
     1, 2, 3 };
    double darr[] = {
     4.2, 5.2 };
    bool barr[] = {
     true, false, true, false };
    QString value = "str";
    QJsonObject obj;
    obj.insert("Name", "Apple");
    obj.insert("Color", "Red");
    obj.insert("Weight", 0.2);

    JSON* json = new JSON();
    json->writeJson("bool", true);
    json->writeJson("int", 1);
    json->writeJson("double", 2.4);
    // value must be QString, implicit conversion turns string literal into bool
    json->writeJson("string", value);
    json->writeJson("str2bool", "str");
    json->writeJson("bool array", barr, 4);
    json->writeJson("int array", arr, 3);
    json->writeJson("double array", darr, 2);
    json->writeJson("object", obj);
    qDebug() << json->getJson();

    json->saveJson("../test.json");

    QWidget* widget = new QWidget();
    QLabel* label = new QLabel();
    label->setText(json->toString());

    QHBoxLayout* hBoxLayout = new QHBoxLayout();
    hBoxLayout->addWidget(label);
    widget->setLayout(hBoxLayout);
    w.setCentralWidget(widget);

    w.show();
    return a.exec();
}

4、 Generated JSON Sample file

{
    
    "bool": true,
    "bool array": [
        true,
        false,
        true,
        false
    ],
    "double": 2.4,
    "double array": [
        4.2,
        5.2
    ],
    "int": 1,
    "int array": [
        1,
        2,
        3
    ],
    "object": {
    
        "Color": "Red",
        "Name": "Apple",
        "Weight": 0.2
    },
    "str2bool": true,
    "string": "str"
}

remarks :mainwindow.h and mainwindow.cpp I'm going to use it directly here Qt Generated by default . The code above needs to pay attention to : about json->writeJson("str2bool", "str"); It will print out "str2bool":true, This is because the string literal will be implicitly "str" Convert to bool type , If you need to print out a string , You must explicitly set the corresponding value to QString type , therefore json->writeJson("string", value); It will print out the expected "string":"str".

Reference documents :

JSON Support in Qt

原网站

版权声明
本文为[Cappuccino-jay]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207052347571800.html