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

运行之后:

相关推荐
Felix_One2 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
范特西.i10 天前
QT聊天项目(8)
开发语言·qt
枫叶丹410 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发10 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun10 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼8810 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x10 天前
Qt中使用Zint库显示二维码
qt
谁刺我心10 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
上海合宙LuatOS10 天前
LuatOS核心库API——【json 】json 生成和解析库
java·前端·网络·单片机·嵌入式硬件·物联网·json