Qt 5读取、解析、生成和保存JSON文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Demorngel/article/details/85089427

项目中用到了一些JSON的东西,为了方便就做了一层简单的封装方便以后使用,包括了JSON的读取、解析、生成和保存这些基本功能
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

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;
}

测试用的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();
}

生成的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
How to create/read/write JSon files in Qt5
Qt 之 JSON 生成与解析
Qt 之高级网络操作(HTTP/FTP 快速上手)

猜你喜欢

转载自blog.csdn.net/Demorngel/article/details/85089427