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

运行之后:

相关推荐
应用市场40 分钟前
Qt QTreeView深度解析:从原理到实战应用
开发语言·数据库·qt
864记忆1 小时前
Qt Widgets 模块中的函数详解
开发语言·qt
彡皮3 小时前
基于Qt,调用千问7B大模型,实现智能对话
开发语言·qt·大模型·千问7b
qq_401700415 小时前
QT的5种标准对话框
开发语言·qt
消失的旧时光-19436 小时前
Kotlinx.serialization 使用指南
android·kotlin·json
rainFFrain6 小时前
qt显示类控件---QCalendarWidget
开发语言·qt
消失的旧时光-19437 小时前
Kotlinx.serialization 项目集成
android·kotlin·json
爱奥尼欧8 小时前
【QT笔记】常用控件——QWidget 核⼼属性
数据库·笔记·qt
大神的风范9 小时前
linux之ubuntu qt界面开发开发点菜系统
linux·qt·ubuntu
大米粥哥哥10 小时前
Qt 使用QAMQP连接RabbitMQ
开发语言·qt·rabbitmq·qamqp