Qt 笔记2--Qt 操作 Json

对着背影说爱祢 提交于 2019-11-30 12:39:25

Qt 笔记2--Qt 操作 Json

 

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于 ECMAScript(欧洲计算机协会制定的js规范)一个子集,采用完全独立于编程语言的文本格式来存储和表示数据,其简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 Qt提供了一系列的Json处理类,包括:QJsonDocument、QJsonObject、QJsonArray、QJsonValue、QJsonParseError,以下为笔者最近学习Qt Json解析功能时写的一些用例,相应学习笔记分享在此处,以便于后续参考。若后续有新的功能或者案例,也会在此处加以补充!

 

1、功能说明

1) Json转字符串--F1Json2String、F2JsonArray2String
2) 创建Json--M1CreateJson、M1CreateJsonV2
3) 创建Json数组--M2CreateJsonArray
4) 查找Json字段--M3FindFromJson
5) 修改Json字段--M4ModifyJson
6) 删除Json字段--M5DeleteItem
7) 添加Json字段--M6AddItem
8) 保存Json到文档--M7SaveJsonToDoc
9) 加载文档中的Json--M8LoadJsonFromDoc

 

2、源代码

代码包括三个主要文件:jsonclass.h、jsonclass.cpp、main.cpp,源码如下:

jsonclass.h

#ifndef JSONCLASS_H
#define JSONCLASS_H

#include <QObject>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonDocument>

#include <QString>
#include <QDebug>
#include <QFile>

class JsonClass
{
public:
    JsonClass();
    QString F1Json2String(QJsonObject obj,int type);
    QString F2JsonArray2String(QJsonArray obj,int type);
    void M1CreateJson();
    void M1CreateJsonV2();
    void TestM1CreateJson(int type);
    void M2CreateJsonArray();
    void TestM2CreateJsonArray();
    void M3FindFromJson();
    void TestM3FindFromJson();
    void M4ModifyJson();
    void TestM4ModifyJson();
    void M5DeleteItem();
    void TestM5DeleteItem();
    void M6AddItem();
    void TestM6AddItem();
    void M7SaveJsonToDoc(QString PathName);
    void TestM7SaveJsonToDoc();
    void M8LoadJsonFromDoc(QString PathName);
    void TestM8LoadJsonFromDoc();

};

#endif // JSONCLASS_H

jsonclass.cpp

#include "jsonclass.h"

JsonClass::JsonClass()
{
    qDebug()<<"Initial JsonClass!";
}

QString JsonClass::F1Json2String(QJsonObject obj,int type=1)
{
    /*
     * 该函数用于将Json对象转为字符串
    */
    QJsonDocument JDobj;
    JDobj.setObject(obj);
    QByteArray bytearrC = JDobj.toJson(QJsonDocument::Compact);//Compact|Indented
    QByteArray bytearrI = JDobj.toJson(QJsonDocument::Indented);
    /*
    qDebug()<<"1-对象格式输出:\n"<<obj;
    qDebug()<<"2-docment格式输出:\n"<<JDobj;
    qDebug()<<"3-bytearray 紧凑型输出:\n"<<bytearrC;
    qDebug()<<"4-bytearray 缩进型输出:\n"<<bytearrI;
    */
    if(type==1)
        return bytearrC.data();
    else
        return bytearrI.data();
}

QString JsonClass::F2JsonArray2String(QJsonArray obj, int type)
{
    /*
     * 该函数用于将JsonArray对象转为字符串
    */
    QJsonDocument JDobj;
    JDobj.setArray(obj);
    QByteArray bytearrC = JDobj.toJson(QJsonDocument::Compact);//Compact|Indented
    QByteArray bytearrI = JDobj.toJson(QJsonDocument::Indented);
    /*
    qDebug()<<"1-对象格式输出:\n"<<obj;
    qDebug()<<"2-docment格式输出:\n"<<JDobj;
    qDebug()<<"3-bytearray 紧凑型输出:\n"<<bytearrC;
    qDebug()<<"4-bytearray 缩进型输出:\n"<<bytearrI;
    */
    if(type==1)
        return bytearrC.data();
    else
        return bytearrI.data();
}

void JsonClass::M1CreateJson()
{
    /*
     * 该函数用于创建一个Json
    */
    QJsonObject objJS;
    qDebug()<<"\nM1:Create Json!";
    qDebug()<<"Empty Json:"<<objJS; //此时为空
    objJS.insert("Name",QString("Jack"));
    objJS.insert("Age",16);
    objJS.insert("Status",true);
    QString objJSstr = F1Json2String(objJS,2);
    qDebug().noquote()<<objJSstr;//noquote()去掉引号和转移符
}

void JsonClass::M1CreateJsonV2()
{
    /*
     * 该函数用于创建一个Json,分别用如下函数:
     * QJsonObject(std::initializer_list<QPair<QString, QJsonValue> > args)
     * QJsonArray(std::initializer_list<QJsonValue> args)
    */
    //JsonObj = {"Name":"Jack","Age":34,"Colleagues":[{"Name":"Tom","Age":44},{"Name":"Abel","Age":29}]};
    QJsonObject JSobj= {{"Name","Jack"},{"Age",34}};
    QJsonObject JSP1 = {{"Name","Tom"},{"Age",44}};
    QJsonObject JSP2 = {{"Name","Abel"},{"Age",29}};
    QJsonArray JAobj = {JSP1,JSP2}; //或者JA0bj={1,2,3}也可以创建JsonArray
     JSobj.insert("Colleagues",JAobj);
    qDebug()<<"\nM1:Create JsonV2!";
    QString StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<StrObj;
}

void JsonClass::TestM1CreateJson(int type)
{
    if(type==1)
        M1CreateJson();
    else if(type==2)
        M1CreateJsonV2();
    else
        M1CreateJson();
}

void JsonClass::M2CreateJsonArray()
{
    /*
     * 该函数用于创建一个JsonArray
    */
    QJsonArray JAobj;
    qDebug()<<"\nM2:Create JsonArray!";
    qDebug()<<"Empty JsonArray:"<<JAobj;
    JAobj.insert(0,"Jack");
    JAobj.insert(1,81); //使用下标的方式添加元素
    JAobj.push_back(82); //使用push_back方式追加原始
    JAobj.insert(JAobj.size(),83);
    QString StrObj = F2JsonArray2String(JAobj,2);
    qDebug().noquote()<<StrObj;
}

void JsonClass::TestM2CreateJsonArray()
{
    M2CreateJsonArray();
}

void JsonClass::M3FindFromJson()
{
    /*
     * 该函数用于查找/获取Json中的某个字段
    */
    QJsonObject JSobj= {{"Name","Jack"},{"Age",34}};
    QJsonObject JSP1 = {{"Name","Tom"},{"Age",44}};
    QJsonObject JSP2 = {{"Name","Abel"},{"Age",29}};
    QJsonArray JAobj = {JSP1,JSP2};
    JSobj.insert("Colleagues",JAobj);
    qDebug()<<"\nM3:Find From Json!";
    qDebug()<<"Jack_Age:"<<JSobj["Age"].toInt()<<endl<<"Colleagues:";
    for(int i=0;i<(JSobj["Colleagues"].toArray()).size();i++)
    {
        QJsonObject tmp =((JSobj["Colleagues"].toArray())[i]).toObject();
        qDebug().noquote()<<tmp["Name"].toString();
    }
}

void JsonClass::TestM3FindFromJson()
{
    M3FindFromJson();
}

void JsonClass::M4ModifyJson()
{
    /*
     * 该函数用于修改Json中的某个字段
    */
    QJsonObject JSobj= {{"Name","Jack"},{"Age",34}};
    QJsonObject JSP1 = {{"Name","Tom"},{"Age",44}};
    QJsonObject JSP2 = {{"Name","Abel"},{"Age",29}};
    QJsonArray JAobj = {JSP1,JSP2};
    JSobj.insert("Colleagues",JAobj);
    qDebug()<<"\nM4:Modify Json!";
    //1)更改Jack Age为36
    JSobj["Age"]=36;//或者 =QJsonValue(36);
    //2)更改Tom Age为36,需要逐层修改对象
    QJsonArray JAtmp =  JSobj["Colleagues"].toArray();
    QJsonObject JStmp = JAtmp[0].toObject();
    JStmp["Age"]=36;
    JAtmp[0] = JStmp;
    JSobj["Colleagues"] = JAtmp;
    QString StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<StrObj;
}

void JsonClass::TestM4ModifyJson()
{
    M4ModifyJson();
}

void JsonClass::M5DeleteItem()
{
    /*
     * 该函数用于删除Json中的某个字段
    */
    QJsonObject JSobj= {{"Name","Jack"},{"Age",34}};
    QJsonObject JSP1 = {{"Name","Tom"},{"Age",44}};
    QJsonObject JSP2 = {{"Name","Abel"},{"Age",29}};
    QJsonArray JAobj = {JSP1,JSP2};
    JSobj.insert("Colleagues",JAobj);
    qDebug()<<"\nM5:Delete Json!";
    QString StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<"Original Json!\n"<<StrObj;
    //ToDo 1删除Tom同事,2删除所有同事
    QJsonArray JAtmp = JSobj["Colleagues"].toArray();
    JAtmp.removeAt(0);
    JSobj["Colleagues"] = JAtmp;
    StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<"Tom has been deleted!\n"<<StrObj;
    JSobj.remove("Colleagues");
    StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<"Colleagues has been deleted!\n"<<StrObj;
}

void JsonClass::TestM5DeleteItem()
{
    M5DeleteItem();
}

void JsonClass::M6AddItem()
{
    /*
     * 该函数用于添加Json中的某个字段
    */
    QJsonObject JSobj= {{"Name","Jack"},{"Age",34}};
    QJsonObject JSP1 = {{"Name","Tom"},{"Age",44}};
    QJsonObject JSP2 = {{"Name","Abel"},{"Age",29}};
    QJsonArray JAobj = {JSP1,JSP2};
    JSobj.insert("Colleagues",JAobj);
    qDebug()<<"\nM6:Add Json!";
    //ToDo 1添加部门信息
    JSobj.insert("Department","CS");
    JSP1.insert("Department","gym");
    JSP2.insert("Department","English");
    JAobj = {JSP1,JSP2};
    JSobj["Colleagues"] = JAobj;
    //2添加新同事Alex
    QJsonObject JSP3 = {{"Name","Alex"},{"Age",23},{"Department","CS"}};
    JAobj.push_back(JSP3);
    JSobj["Colleagues"] = JAobj;
    QString StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<StrObj;
}

void JsonClass::TestM6AddItem()
{
    M6AddItem();
}

void JsonClass::M7SaveJsonToDoc(QString PathName)
{
    /*
     * 该函数用于保存Json到某个文件
    */
    QJsonObject JSobj= {{"Name","Jack"},{"Age",34}};
    QJsonObject JSP1 = {{"Name","Tom"},{"Age",44}};
    QJsonObject JSP2 = {{"Name","Abel"},{"Age",29}};
    QJsonArray JAobj = {JSP1,JSP2};
    JSobj.insert("Colleagues",JAobj);
    qDebug()<<"\nM7:Save Json!";
    QString StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<"Original Json!\n"<<StrObj;
    QFile file(PathName);
    if(!file.open(QIODevice::WriteOnly))
    {
        qDebug()<<"Write file error!";
    }
    QJsonDocument JDobj(JSobj);
    QByteArray Qba = JDobj.toJson(QJsonDocument::Indented);
    file.write(Qba);
    file.close();
    qDebug().noquote()<<"Write Json to "<<PathName <<" done!";
}

void JsonClass::TestM7SaveJsonToDoc()
{
    M7SaveJsonToDoc("Save.json");

}

void JsonClass::M8LoadJsonFromDoc(QString PathName)
{
    /*
     * 该函数用于从某个文件读取Json
    */

    qDebug()<<"\nM8:Load Json!";
    QFile file(PathName);
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"Read file error!";
    }
    QByteArray Qba = file.readAll();
    file.close();
    QJsonDocument JDobj = QJsonDocument::fromJson(Qba);
    QJsonObject JSobj = JDobj.object();
    qDebug().noquote()<<"Load Json from "<<PathName <<" done!";
    QString StrObj = F1Json2String(JSobj,2);
    qDebug().noquote()<<StrObj;
}

void JsonClass::TestM8LoadJsonFromDoc()
{
    M8LoadJsonFromDoc("./Save.json");
}

main.cpp

#include <QCoreApplication>
#include "jsonclass.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    JsonClass *JCobj = new JsonClass();

    JCobj->TestM1CreateJson(2);
    JCobj->TestM2CreateJsonArray();
    JCobj->TestM3FindFromJson();
    JCobj->TestM4ModifyJson();
    JCobj->TestM5DeleteItem();
    JCobj->TestM6AddItem();
    JCobj->TestM7SaveJsonToDoc();
    JCobj->TestM8LoadJsonFromDoc();
    delete JCobj;
    return a.exec();
}

3、测试结果

2) 创建Json

M1:Create JsonV2!
{
    "Age": 34,
    "Colleagues": [
        {
            "Age": 44,
            "Name": "Tom"
        },
        {
            "Age": 29,
            "Name": "Abel"
        }
    ],
    "Name": "Jack"
}

3)创建Json数组

M2:Create JsonArray!
Empty JsonArray: QJsonArray()
[
    "Jack",
    81,
    82,
    83
]

4)查找Json字段

M3:Find From Json!
Jack_Age: 34
Colleagues:
Tom
Abel

5)修改Json字段

M4:Modify Json!
{
    "Age": 36,
    "Colleagues": [
        {
            "Age": 36,
            "Name": "Tom"
        },
        {
            "Age": 29,
            "Name": "Abel"
        }
    ],
    "Name": "Jack"
}

6)删除Json字段

M5:Delete Json!
Original Json!
 {
    "Age": 34,
    "Colleagues": [
        {
            "Age": 44,
            "Name": "Tom"
        },
        {
            "Age": 29,
            "Name": "Abel"
        }
    ],
    "Name": "Jack"
}

Tom has been deleted!
 {
    "Age": 34,
    "Colleagues": [
        {
            "Age": 29,
            "Name": "Abel"
        }
    ],
    "Name": "Jack"
}

Colleagues has been deleted!
 {
    "Age": 34,
    "Name": "Jack"
}

7)添加Json字段

M6:Add Json!
{
    "Age": 34,
    "Colleagues": [
        {
            "Age": 44,
            "Department": "gym",
            "Name": "Tom"
        },
        {
            "Age": 29,
            "Department": "English",
            "Name": "Abel"
        },
        {
            "Age": 23,
            "Department": "CS",
            "Name": "Alex"
        }
    ],
    "Department": "CS",
    "Name": "Jack"
}

8)保存Json到文档

M7:Save Json!
Original Json!
 {
    "Age": 34,
    "Colleagues": [
        {
            "Age": 44,
            "Name": "Tom"
        },
        {
            "Age": 29,
            "Name": "Abel"
        }
    ],
    "Name": "Jack"
}

Write Json to  Save.json  done!

9)加载文档中的Json

M8:Load Json!
Load Json from  ./Save.json  done!
{
    "Age": 34,
    "Colleagues": [
        {
            "Age": 44,
            "Name": "Tom"
        },
        {
            "Age": 29,
            "Name": "Abel"
        }
    ],
    "Name": "Jack"
}

 

4、说明

以上代码默认测试环境为Qt 5.7,测试系统为Windows7 x64

参考文献:
[1] QT5处理 json 总结 : https://blog.csdn.net/dijkstar/article/details/81902562
[2] Qt Documentation : https://doc.qt.io/qt-5/classes.html#j

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!