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()<<"失败";
    }

运行之后:

相关推荐
敲上瘾12 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
ShineWinsu13 小时前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog
JosieBook18 小时前
【鸿蒙】把一个 Qt 桌面视频编辑器“搬“上鸿蒙 PC:Olive 移植适配全记录
qt·音视频·harmonyos
麻瓜code18 小时前
流式返回的工具参数是一段一段来的,怎么拼成一个 JSON
json
Lucas. Wáng2 天前
Qt学习之旅
c++·qt
金色熊族2 天前
qt5.15.9编译qt-creator7.0.2源码
linux·qt
ShineWinsu3 天前
对于Qt:QMessageBox的解析
开发语言·c++·qt·面试·客户端·qmessagebox·消息对话框
鲸渔3 天前
【AI Agent系列课程13-Python 基础13】JSON 读写:结构化数据交换基础
开发语言·python·json·ai编程
宏笋3 天前
Qt开发了一款绘图和制作信笺的软件
qt
半杯咖啡半行码4 天前
Qt 隐式共享(Implicit Sharing)深度解析:机制、陷阱与 Qt6迁移
开发语言·数据库·qt