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

运行之后:

相关推荐
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_2 天前
QT(4)
开发语言·汇编·c++·qt·算法
lqjun08273 天前
Qt程序单独运行报错问题
开发语言·qt
酷飞飞3 天前
Qt Designer与事件处理
开发语言·qt·命令模式
mkhase3 天前
9.12-QT-基本登陆界面实现
java·jvm·qt
Martin-Luo3 天前
Vue3 通过json配置生成查询表单
javascript·vue.js·json
咕噜咕噜啦啦3 天前
Qt之快捷键、事件处理、自定义按键——完成记事本项目
开发语言·qt
星尘库3 天前
后端json数据反序列化枚举类型不匹配的错误
json
BXCQ_xuan3 天前
软件工程实践四:MyBatis-Plus 教程(连接、分页、查询)
spring boot·mysql·json·mybatis
Quz3 天前
QML Charts组件之折线图的鼠标交互
qt