当前位置: 首页 > 工具软件 > Qjson > 使用案例 >

【QT】Qt使用QJson生成json文件并保存

荣俊杰
2023-12-01

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);
	//根据实际填写路径
	QFile file("D:\\1.json");
 
	if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
	{
		qDebug() << "file error!";
	}
	QTextStream in(&file);
	in << json_str;
 
	file.close();   // 关闭file
}

Sample 2:

新建一个QT空项目:

#include <QCoreApplication>

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

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

#pragma execution_character_set("utf-8") // qt支持显示中文

// 封装Json
void createJson() {
    /*
     *		"interest": {
     *			"basketball": "篮球",
     *			"badminton": "羽毛球"
     *		 },
     */
    // 定义 { } 对象
    QJsonObject interestObj;
    // 插入元素,对应键值对
    interestObj.insert("basketball", "篮球");
    interestObj.insert("badminton", "羽毛球");

    /*
     *		"color": [ "black", "white"],
     */
    // 定义 [ ] 数组
    QJsonArray colorArray;
    // 往数组中添加元素
    colorArray.append("black");
    colorArray.append("white");

    /*
     *		"like": [
     *			{ "game": "三国杀", "price": 58.5 },
     *			{ "game": "海岛奇兵", "price": 66.65 }
     *		],
     */
    // 定义 { } 对象
    QJsonObject likeObject1;
    likeObject1.insert("game", "三国杀");
    likeObject1.insert("price", 58.5);
    
    QJsonObject likeObject2;
    likeObject2.insert("game", "海岛奇兵");
    likeObject2.insert("price", 66.65);

    // 定义 [ ] 对象
    QJsonArray likeArray;
    likeArray.append(likeObject1);
    likeArray.append(likeObject2);

    /*
     *		"languages": {
     *			"serialOne": { "language": "汉语", "grade": 10 },
     *			"serialTwo": { "language": "英语", "grade": 6 }
     *		},
     */
    // 定义 { } 对象
    QJsonObject language1;
    language1.insert("language", "汉语");
    language1.insert("grade", 10);

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

    QJsonObject languages;
    // 将{ } 插入 { } 中
    languages.insert("serialOne", language1);
    languages.insert("serialTwo", language2);

    // 定义根节点	也即是最外层 { }
    QJsonObject rootObject;

    // 插入元素
    rootObject.insert("name", "老王");
    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);

    // 将json对象里的数据转换为字符串
    QJsonDocument doc;
    // 将object设置为本文档的主要对象
    doc.setObject(rootObject);

    // Json字符串保存到json文件里
    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");		// 设置写入编码是UTF8
    // 写入文件
    stream << doc.toJson();
    file.close();
}

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

    // 读取文件的全部内容
    QTextStream stream(&file);
    stream.setCodec("UTF-8");		// 设置读取编码是UTF8
    QString str = stream.readAll();

    file.close();

    /* 解析Json */

    // QJsonParseError类用于在JSON解析期间报告错误。
    QJsonParseError jsonError;
    // 将json解析为UTF-8编码的json文档,并从中创建一个QJsonDocument。
    // 如果解析成功,返回QJsonDocument对象,否则返回null
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(), &jsonError);
    // 判断是否解析失败
    if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
        qDebug() << "Json格式错误!" << jsonError.error;
        return;
    }

    // 获取根 { }
    QJsonObject rootObj = doc.object();

    // 根据键获取值
    QJsonValue nameValue = rootObj.value("name");
    qDebug() << "name = " << nameValue.toString();

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

    // 解析对象 { }
    QJsonValue interestValue = rootObj.value("interest");
    // 判断是否是object类型
    if (interestValue.type() == QJsonValue::Object) {
        // 转换为QJsonObject类型
        QJsonObject interestObj = interestValue.toObject();

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

    // 解析数组 [ ]
    QJsonValue colorValue = rootObj.value("color");
    // 判断是否是Array类型
    if (colorValue.type() == QJsonValue::Array) {
        // 转换为QJsonArray类型
        QJsonArray colorArray = colorValue.toArray();

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

    // 解析数组中的对象 [ { } ]
    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();
            }
        }
    }

    // 解析 对象 中 对象 { { } }
    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();
        }
    }

    // 解析 bool类型
    QJsonValue vipValue = rootObj.value("vip");
    qDebug() << "vip = " << vipValue.toBool();


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

}

// 修改Json数据
void alterJson() {
    /* 修改也就再重写写一遍覆盖掉就行 */

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

    // 读取文件的全部内容
    QTextStream readStream(&readFile);
    readStream.setCodec("UTF-8");		// 设置读取编码是UTF8
    QString str = readStream.readAll();
    readFile.close();

    /* 修改Json */

    // QJsonParseError类用于在JSON解析期间报告错误。
    QJsonParseError jsonError;
    // 将json解析为UTF-8编码的json文档,并从中创建一个QJsonDocument。
    // 如果解析成功,返回QJsonDocument对象,否则返回null
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
        qDebug() << "Json格式错误!" << jsonError.error;
        return;
    }

    // 获取根 { }
    QJsonObject rootObj = doc.object();

    // 修改name属性
    rootObj["name"] = "老李";
    rootObj["vip"] = false;


    // 修改数组[]中的元素
    QJsonValue colorValue = rootObj.value("color");
    if (colorValue.type() == QJsonValue::Array) {
        QJsonArray colorArray = colorValue.toArray();

        // 修改数组中的值
        colorArray.replace(0, "blue");
        colorArray.replace(1, "green");

        // 赋值覆盖原有数组属性
        rootObj["color"] = colorArray;
    }

    // 修改 { } 中的值
    QJsonValue interestValue = rootObj.value("interest");
    if (interestValue.type() == QJsonValue::Object) {
        QJsonObject interestObject = interestValue.toObject();

        interestObject["badminton"] = "乒乓球";
        interestObject["basketball"] = "足球";

        rootObj["interest"] = interestObject;
    }


    // 修改 { { } } 中的值
    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();

            serialOneObj["grade"] = "20";

            languagesObj["serialOne"] = serialOneObj;
        }

        // 找到内部第二个 { }
        QJsonValue serialTwoValue = languagesObj.value("serialTwo");
        if (serialTwoValue.type() == QJsonValue::Object) {
            QJsonObject serialTwoObj = serialTwoValue.toObject();

            serialTwoObj["grade"] = "10";
            serialTwoObj["language"] = "粤语";

            languagesObj["serialTwo"] = serialTwoObj;
        }

        rootObj["languages"] = languagesObj;
    }

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

        // 根据索引获得对应{ }
        QJsonObject obj1 = likeArray[0].toObject();
        obj1["game"] = "欢乐斗地主";
        obj1["price"] = 88.8;
        QJsonObject obj2 = likeArray[1].toObject();
        obj2["game"] = "欢乐斗牛";
        obj2["price"] = 77.7;

        // 替换覆盖
        likeArray.replace(0, obj1);
        likeArray.replace(1, obj2);

        rootObj["like"] = likeArray;
    }

    // 将object设置为本文档的主要对象
    doc.setObject(rootObj);

    // 重写打开文件,覆盖原有文件,达到删除文件全部内容的效果
    QFile writeFile("../Json/js.json");
    if (!writeFile.open(QFile::WriteOnly | QFile::Truncate)) {
        qDebug() << "can't open error!";
        return;
    }

    // 将修改后的内容写入文件
    QTextStream wirteStream(&writeFile);
    wirteStream.setCodec("UTF-8");		// 设置读取编码是UTF8
    wirteStream << doc.toJson();		// 写入文件
    writeFile.close();					// 关闭文件
}

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

    // 读取文件的全部内容
    QTextStream readStream(&readFile);
    readStream.setCodec("UTF-8");		// 设置读取编码是UTF8
    QString str = readStream.readAll();
    readFile.close();

    /* 修改Json */

    // QJsonParseError类用于在JSON解析期间报告错误。
    QJsonParseError jsonError;
    // 将json解析为UTF-8编码的json文档,并从中创建一个QJsonDocument。
    // 如果解析成功,返回QJsonDocument对象,否则返回null
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError && !doc.isNull()) {
        qDebug() << "Json格式错误!" << jsonError.error;
        return;
    }

    // 获取根 { }
    QJsonObject rootObj = doc.object();


    // 删除age
    rootObj.remove("age");


    // 删除数组[]中的元素
    QJsonValue colorValue = rootObj.value("color");
    if (colorValue.type() == QJsonValue::Array) {
        QJsonArray colorArray = colorValue.toArray();

        // 删除数组中索引为1的值
        colorArray.removeAt(1);

        // 赋值覆盖原有数组属性
        rootObj["color"] = colorArray;
    }

    // 删除 { } 中的值
    QJsonValue interestValue = rootObj.value("interest");
    if (interestValue.type() == QJsonValue::Object) {
        QJsonObject interestObject = interestValue.toObject();

        // 删除键为basketball的属性元素
        interestObject.remove("basketball");

        rootObj["interest"] = interestObject;
    }
    
    // 删除 { { } } 中的值
    QJsonValue languagesValue = rootObj.value("languages");
    if (languagesValue.type() == QJsonValue::Object) {
        QJsonObject languagesObj = languagesValue.toObject();

        // 删除键为serialTwo的对象 { }
        languagesObj.remove("serialTwo");

        rootObj["languages"] = languagesObj;
    }

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

        // 删除索引为1数组中的值
        likeArray.removeAt(1);

        rootObj["like"] = likeArray;
    }

    // 删除 [ ]
    rootObj.remove("color");

    // 删除 { }
    rootObj.remove("interest");

    // 将object设置为本文档的主要对象
    doc.setObject(rootObj);

    // 重写打开文件,覆盖原有文件,达到删除文件全部内容的效果
    QFile writeFile("../Json/js.json");
    if (!writeFile.open(QFile::WriteOnly | QFile::Truncate)) {
        qDebug() << "can't open error!";
        return;
    }

    // 将修改后的内容写入文件
    QTextStream wirteStream(&writeFile);
    wirteStream.setCodec("UTF-8");		// 设置读取编码是UTF8
    wirteStream << doc.toJson();		// 写入文件
    writeFile.close();					// 关闭文件
}

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

    createJson();

    analysisJson();

    alterJson();

    delJson();

    return a.exec();
}

备注:指定编码 #pragma execution_character_set(“utf-8”) // qt支持显示中文

Sample 3:(一个 json 对象含多个数组)

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;         //存储当前json
    QHash<QString, QStringList> m_defaultHash;      //存储默认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); //函数说明:解析UTF-8编码的JSON文档并从中创建QJsonDocument。

            if (document.isNull() || (jsonError.error != QJsonParseError::NoError))
            {
                qDebug() << "document error";
                break;
            }
            if (jsonError.error == QJsonParseError::IllegalUTF8String)                  //输入中出现非法UTF8序列
            {
                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封装:包括了JSON的读取、解析、生成和保存这些基本功能

1、json.h文件

#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文件

#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文件(数据测试)

#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、生成的JSON文件样例

{
    "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"
}

备注:mainwindow.h和mainwindow.cpp这里直接使用Qt默认生成的就可以。上面的代码需要注意的是:对于json->writeJson("str2bool", "str");它将打印出"str2bool":true,这是因为这里会隐式的将字符串字面量"str"转换为bool类型,如果需要打印出字符串,就必须显式的将相应的值设置为QString类型,因此json->writeJson("string", value);会打印出期望的"string":"str"

参考文档:

JSON Support in Qt

 类似资料: