Qt之Json操作demo

一、JSON简介:

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,使用JavaScript语法来描述数据对象,但是JSON仍然独立于语言和平台。JSON解析器和JSON库支持许多不同的编程语言,被广泛用于Internet上的数据交换格式。

    JSON的语法主要是:
        1)键值对(key:value)
              键值key,必须是字符串,位于同一层级的键值,不能重复;
              value值,类型是可选的,整形,浮点型,字符串,json数组,json对象,空值-null(null)。
        2)元素和元素之间使用 , 间隔,最后一个元素后面没有 ,
        3)花括号保存对象,每个Json对象可以存储若干个元素
        4)方括号保存数组,数组内的元素类型可以不一致
        5)json文档始终以方括号或大括号开头

    官网:http://json.org/

二、QT中的JSON:

qt中的json类:

1)QJsonDocument:

提供读取和写入JSON文档的方法,可以通过成员函数array()和object()检索文档中包含的数组和对象,读取数据或修改数据。
使用上例如:
    QJsonObject obj;
    obj.insert(“name”,QString(“Test”));
    QJsonDocument doc(obj); //将Json对象,转换成Json文档
    //显示用
    QByteArray json = doc.toJson();
    ui.textEdit->setText(json);
    //写入文件
    QFile file(“…/my.json”);
    file.open(QFile::WriteOnly);
    file.write(json);
    file.close();

2)QJsonObject:

封装了Json中的对象,在里边可以存储多个键值对,为了方便操作,键值为字符串类型,值为QJsonValue类型。QJsonObject内数据使用insert插入,根据key值,自动排序,底层红黑树,升序。
使用上例如:
    QJsonObject obj;
    obj.insert(“name”,QString(“Test”));
    obj.insert(“sex”,QString(“Man”));

常用遍历方法:
    1)使用迭代器函数:QJsonObject::iterator
    2)使用 [] 的方式遍历,类似于遍历数组,[] 中是键值

常用方法:
    1)获取对象中键值对个数:int QJsonObject::count() const;
    2)通过 key 得到 value:QJsonValue QJsonObject::value(const QString &key) const;
    3)通过key进行查找:bool QJsonObject::contains(const QString &key) const;
    4)将键值对添加到空对象中:iterator QJsonObject::insert(const QString &key, const QJsonValue &value);

3)QJsonValue:

基本数据类型:
    1)bool
    2)double
    3)string
    4)array
    5)object
    6)null

常用函数:
    1)判断数据类型:

    // 是否是Json数组
    bool isArray() const;

    // 是否是Json对象
    bool isObject() const;

    // 是否是布尔类型
    bool isBool() const;

    // 是否是浮点类型(整形也是通过该函数判断)
    bool isDouble() const;

    // 是否是空值类型
    bool isNull() const;

    // 是否是字符串类型
    bool isString() const;

    // 是否是未定义类型(无法识别的类型)
    bool isUndefined() const;

    2)转换数据类型:
    // 转换为Json数组
    QJsonArray toArray(const QJsonArray &defaultValue) const;
    QJsonArray toArray() const;

    // 转换为布尔类型
    bool toBool(bool defaultValue = false) const;

    // 转换为浮点类型
    double toDouble(double defaultValue = 0) const;

    // 转换为整形
    int toInt(int defaultValue = 0) const;

    // 转换为Json对象
    QJsonObject toObject(const QJsonObject &defaultValue) const;
    QJsonObject toObject() const;

    // 转换为字符串类型
    QString toString() const;
    QString toString(const QString &defaultValue) const;

4)QJsonArray:

封装了Json数组,里面存储多个元素,为了方便操作,所有元素类型统一为QJsonValue类型。
使用上例如:
    QJsonObject obj;
    obj.insert(“Name”,QString(“Test”));
    QJsonArray array;
    array.append(QString(“1”));
    array.append(QString(“2”));
    obj.insert(“Number”,array);

QT-Json与Jsoncpp对比:
    性能上的话,QT-Json会比Jsoncpp好,QT-Json严格按照ECMA-404 协议的解析范本,Jsoncpp比较随意。Qt-Json允许设置默认值,对于无法转换成功的,不抛异常,而Jsoncpp不允许设置默认值,对于无法转换成功的,会抛异常。QT-Json支持的Json文本最大不能超过128M,嵌套层不能超过1024层。在错误信息上,QT-Json不能定位到具体行列,Jsoncpp可以定位到行列。

三、json-demo:

1)界面

在这里插入图片描述

2)核心代码

ctjson.h

#ifndef CTJSON_H
#define CTJSON_H

#include <QObject>
#include "commondef.h"

class CtJson : public QObject
{
    Q_OBJECT
public:
    CtJson();
    ~CtJson();
    static CtJson& getInstance();

signals:
    void sig_returnJsonData(PERSION_T stPersion);
    void sig_showJsonData(QByteArray jsonData);

public slots:
    void on_writeToJsonFile(PERSION_T stPersion);
    void on_readFromJsonFile();

};

#endif // CTJSON_H

ctjson.cpp

#include "ctjson.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QMessageBox>

CtJson::CtJson()
{
}

CtJson::~CtJson()
{
}

CtJson &CtJson::getInstance()
{
    static CtJson s_obj;
    return s_obj;
}

void CtJson::on_writeToJsonFile(PERSION_T stPersion)
{
    QJsonObject jsonObj;
    {
        jsonObj.insert("Name", stPersion.sName);
        jsonObj.insert("Age", stPersion.nAge);
        jsonObj.insert("Sex", stPersion.Sex);
        jsonObj.insert("Height", stPersion.nHeight);
        jsonObj.insert("Weight", stPersion.nWeight);
    }

    QJsonObject familyObj;
    {
        familyObj.insert("Father", stPersion.family.sFather);
        familyObj.insert("Mother", stPersion.family.sMother);
        QJsonArray BrotherArray;
        BrotherArray.append(stPersion.family.sBrother.at(0));
        BrotherArray.append(stPersion.family.sBrother.at(1));
        BrotherArray.append(stPersion.family.sBrother.at(2));
        familyObj.insert("Brothers", BrotherArray);
    }
    jsonObj.insert("Family", familyObj);

    QJsonDocument jDoc(jsonObj);
    QByteArray jsonData = jDoc.toJson();

    QFile file(JSON_FILE_PATH);
    if(!file.open(QIODevice::WriteOnly))
    {
        MY_DEBUG << "Open Json File Failed.";
        return;
    }
    file.write(jsonData);
    file.close();

    emit sig_showJsonData(jsonData);
}

void CtJson::on_readFromJsonFile()
{
    QFile file(JSON_FILE_PATH);
    if(!file.open(QIODevice::ReadOnly))
    {
        MY_DEBUG << "Open Json File Failed";
        return;
    }

    QByteArray fileData = file.readAll();
    file.close();

    QJsonParseError jError;
    QJsonDocument jDoc = QJsonDocument::fromJson(fileData, &jError);//转换成文档对象
    if(jError.error != QJsonParseError::NoError)
    {
        MY_DEBUG << "Json File Error.";
        return;
    }

    PERSION_T stPersion;
    if(jDoc.isObject())
    {
        QJsonObject jsonObj = jDoc.object();//得到Json对象
        stPersion.sName = jsonObj["Name"].toString();
        stPersion.nAge = jsonObj["Age"].toInt();
        stPersion.Sex = jsonObj["Sex"].toString();
        stPersion.nWeight = jsonObj["Weight"].toInt();
        stPersion.nHeight = jsonObj["Height"].toInt();

        QStringList keys = jsonObj.keys();//得到所有key
        for (int i = 0; i < keys.size(); i++)
        {
            QString key = keys.at(i);
            QJsonValue value = jsonObj.value(key);
            if(value.isObject())
            {
                QJsonObject subObj = value.toObject();
                QStringList subKeys = subObj.keys();
                for(int j = 0; j < subKeys.size(); ++j)
                {
                    QString subkey = subKeys.at(j);
                    QJsonValue subValue = subObj.value(subkey);
                    if(subValue.isString())
                    {
                        if(!subkey.compare("Father"))
                        {
                            stPersion.family.sFather = subValue.toString();
                        }
                        else if(!subkey.compare("Mother"))
                        {
                            stPersion.family.sMother = subValue.toString();
                        }
                    }
                    else if(subValue.isArray())
                    {
                        QJsonArray array = subValue.toArray();
                        for (int k = 0; k < array.size(); k++)
                        {
                            stPersion.family.sBrother.append(array[k].toString());
                        }
                    }
                }
            }

        }
    }
    emit sig_returnJsonData(stPersion);
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "commondef.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

signals:
    void sig_writeToJsonFile(PERSION_T stPersion);
    void sig_readFromJsonFile();

public slots:
    void on_returnJsonData(PERSION_T stPersion);
    void on_showJsonData(QByteArray jsonData);

private slots:
    void on_pushButton_Save_clicked();

    void on_pushButton_Read_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ctjson.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    qRegisterMetaType<PERSION_T>("PERSION_T");

    connect(&CtJson::getInstance(), SIGNAL(sig_returnJsonData(PERSION_T)),
            this, SLOT(on_returnJsonData(PERSION_T)));
    connect(&CtJson::getInstance(), SIGNAL(sig_showJsonData(QByteArray)),
            this, SLOT(on_showJsonData(QByteArray)));
    connect(this, SIGNAL(sig_writeToJsonFile(PERSION_T)),
            &CtJson::getInstance(), SLOT(on_writeToJsonFile(PERSION_T)));
    connect(this, SIGNAL(sig_readFromJsonFile()),
            &CtJson::getInstance(), SLOT(on_readFromJsonFile()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_returnJsonData(PERSION_T stPersion)
{
    ui->lineEdit_Name->setText(stPersion.sName);
    ui->lineEdit_Age->setText(QString::number(stPersion.nAge));
    ui->lineEdit_Sex->setText(stPersion.Sex);
    ui->lineEdit_Height->setText(QString::number(stPersion.nHeight));
    ui->lineEdit_Weight->setText(QString::number(stPersion.nWeight));
    ui->lineEdit_Father->setText(stPersion.family.sFather);
    ui->lineEdit_Mother->setText(stPersion.family.sMother);
    ui->lineEdit_Brother1->setText(stPersion.family.sBrother.at(0));
    ui->lineEdit_Brother2->setText(stPersion.family.sBrother.at(1));
    ui->lineEdit_Brother3->setText(stPersion.family.sBrother.at(2));
}

void MainWindow::on_showJsonData(QByteArray jsonData)
{
    ui->textEdit_JsonShow->setText(jsonData);
}

void MainWindow::on_pushButton_Save_clicked()
{
    PERSION_T stPersion;
    stPersion.sName = ui->lineEdit_Name->text();
    stPersion.nAge = ui->lineEdit_Age->text().toInt();
    stPersion.Sex = ui->lineEdit_Sex->text();
    stPersion.nHeight = ui->lineEdit_Height->text().toInt();
    stPersion.nWeight = ui->lineEdit_Weight->text().toInt();
    stPersion.family.sFather = ui->lineEdit_Father->text();
    stPersion.family.sMother = ui->lineEdit_Mother->text();
    stPersion.family.sBrother.append(ui->lineEdit_Brother1->text());
    stPersion.family.sBrother.append(ui->lineEdit_Brother2->text());
    stPersion.family.sBrother.append(ui->lineEdit_Brother3->text());

    emit sig_writeToJsonFile(stPersion);
}

void MainWindow::on_pushButton_Read_clicked()
{
    emit sig_readFromJsonFile();
}

3)JSON文件

在这里插入图片描述

4)demo下载

下载地址:https://download.csdn.net/download/linyibin_123/87366418?spm=1001.2014.3001.5503

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浅笑一斤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值