Qt 中Json文件的操作

Json文件的读取

cpp 复制代码
    QFile file("data.json"); //准备好的文件

    file.open(QIODevice::ReadOnly|QIODevice::Text);
    QByteArray arr = file.readAll();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(arr);
    QJsonObject jsonObj = jsonDoc.object();

    qint32 id = jsonObj["id"].toInt();
    QString glassid = jsonObj["Glassid"].toString();
    bool result = jsonObj["Result"].toBool();
    qDebug()<<id<<glassid<<result;

提前准备的文件内容:

Json文件的写入

cpp 复制代码
//根据情况设定所需要的类,并实现tojson方法 
class Person
{
public:
    Person();
    Person(int id,QString Glassid,bool Result);
    int Id;
    QString Glassid;
    bool Result;

    QJsonObject tojson()const{  //实现方法
        QJsonObject obj;
        obj["id"]=this->Id;
        obj["Glassid"]=this->Glassid;
        obj["Result"]=this->Result;
        return obj;
    }
};


    person = Person(10,"20310120727",false); //Person的构造函数
    QJsonObject obj1 = person.tojson();;
    QJsonDocument jsonDoc1(obj1);

    QFile file1("data.json");
    if(file1.open(QIODevice::WriteOnly|QIODevice::Text)){
        file1.write(jsonDoc1.toJson());
        file1.close();
    }
    else {
        qDebug()<<"失败";
    }

运行之后:

相关推荐
teacher伟大光荣且正确2 小时前
Qt Creator 配置 Android 编译环境
android·开发语言·qt
六bring个六6 小时前
qtcreater配置opencv
c++·qt·opencv·计算机视觉·图形渲染·opengl
纯纯沙口6 小时前
Qt—多线程基础
开发语言·qt
yxc_inspire7 小时前
基于Qt的app开发第八天
开发语言·c++·qt
9527华安8 小时前
紫光同创FPGA实现AD7606数据采集转UDP网络传输,提供PDS工程源码和技术支持和QT上位机
网络·qt·fpga开发·udp·紫光同创·ad7606
yxc_inspire8 小时前
基于Qt的app开发第七天
开发语言·c++·qt·app
dot to one10 小时前
Qt 中 QWidget涉及的常用核心属性介绍
开发语言·c++·qt
码农新猿类11 小时前
初入OpenCV
qt·opencv·计算机视觉
洛克希德马丁13 小时前
QLineEdit增加点击回显功能
c++·qt·ui
向日葵xyz14 小时前
Qt5与现代OpenGL学习(十一)OpenGL Widget鼠标控制直线旋转
开发语言·qt·学习