在Qt5中创建、读取和写入JSON文件的完整指南

Qt5 提供了一个非常方便的JSON解析器,使得在C++中处理JSON数据变得非常简单。本文将详细介绍如何在Qt5中创建、读取和写入JSON文件。

读取JSON文件的示例

假设我们有一个名为test.json的JSON文件,内容如下:

{
   "appDesc": {
      "description": "SomeDescription",
      "message": "SomeMessage"
   },
   "appName": {
      "description": "Home",
      "message": "Welcome",
      "imp": ["awesome", "best", "good"]
   }
}

我们可以通过以下代码读取这个JSON文件:

void readJson() {
    QString val;
    QFile file;
    file.setFileName("test.json");
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    val = file.readAll();
    file.close();

    qWarning() << val;
    QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
    QJsonObject sett2 = d.object();
    QJsonValue value = sett2.value(QString("appName"));
    qWarning() << value;
    QJsonObject item = value.toObject();
    qWarning() << tr("QJsonObject of description: ") << item;

    // 获取字符串值并转换为字符串
    qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
    QJsonValue subobj = item["description"];
    qWarning() << subobj.toString();

    // 获取数组值并转换为字符串
    qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
    QJsonArray test = item["imp"].toArray();
    qWarning() << test[1].toString();
}

执行上述代码后,控制台输出如下:

QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "Welcome"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "Welcome"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]))
"best"

解析JSON字符串的示例

我们也可以将一个JSON字符串解析为JSON对象:

void readJsonFromString() {
    QString jsonString = R"(
    {
        "appDesc": {
            "description": "SomeDescription",
            "message": "SomeMessage"
        },
        "appName": {
            "description": "Home",
            "message": "Welcome",
            "imp": ["awesome", "best", "good"]
        }
    })";

    QJsonDocument d = QJsonDocument::fromJson(jsonString.toUtf8());
    QJsonObject sett2 = d.object();
    QJsonValue value = sett2.value(QString("appName"));
    qWarning() << value;
    QJsonObject item = value.toObject();
    qWarning() << tr("QJsonObject of description: ") << item;

    qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
    QJsonValue subobj = item["description"];
    qWarning() << subobj.toString();

    qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
    QJsonArray test = item["imp"].toArray();
    qWarning() << test[1].toString();
}

创建和写入JSON文件的示例

下面的代码展示了如何创建一个带有结构的JSON文件:

void createJson() {
    QFile file(QDir::homePath() + "/1.json");
    if(!file.open(QIODevice::ReadWrite)) {
        qDebug() << "File open error";
    } else {
        qDebug() << "File open!";
    }

    // 清空文件内容
    file.resize(0);

    // 创建JSON数组,并写入到文件
    QJsonArray jsonArray;

    for(int i = 0; i < 10; i++) {
        QJsonObject jsonObject;
        jsonObject.insert("Date", QDateTime::currentDateTime().toString());
        jsonObject.insert("Band", "20");

        QJsonObject jsonSenderLatObject;
        jsonSenderLatObject.insert("Lat", 13);
        jsonSenderLatObject.insert("Lon", 122);
        jsonSenderLatObject.insert("Sender", "DX0HQ");

        QJsonObject jsonReceiverLatObject;
        jsonReceiverLatObject.insert("Lat", 36.400001525878906);
        jsonReceiverLatObject.insert("Lon", 138.3800048828125);
        jsonReceiverLatObject.insert("Receiver", "8N3HQ");

        jsonObject.insert("Receiver", jsonReceiverLatObject);
        jsonObject.insert("Sender", jsonSenderLatObject);
        jsonArray.append(jsonObject);
    }

    QJsonObject finalObject;
    finalObject.insert("number", jsonArray.size());
    jsonArray.append(finalObject);

    QJsonDocument jsonDoc;
    jsonDoc.setArray(jsonArray);
    file.write(jsonDoc.toJson());
    file.close();
    qDebug() << "Write to file";
}

输出的JSON文件内容如下:

[
    {
        "Band": "20",
        "Date": "Sat Jul 10 12:00:00 2021",
        "Receiver": {
            "Lat": 36.400001525878906,
            "Lon": 138.3800048828125,
            "Receiver": "8N3HQ"
        },
        "Sender": {
            "Lat": 13,
            "Lon": 122,
            "Sender": "DX0HQ"
        }
    },
    // 其他条目省略
    {
        "number": 10
    }
]
  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

应用市场

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值