基础用法
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
QString APPnameValue = "";
QString DeviceID = "";
QString BatteryID = "";
void DetectionWorker::readJson(const QString &filePath)
{
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "Could not open file for reading:" << file.errorString();
return;
}
QByteArray jsonData = file.readAll();
file.close();
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
if (jsonDoc.isNull()) {
qWarning() << "Failed to create JSON doc.";
return;
}
if (!jsonDoc.isObject()) {
qWarning() << "JSON is not an object.";
return;
}
QJsonObject jsonObj = jsonDoc.object();
// 读取 "Appname" 键的值
if (jsonObj.contains("Appname")) {
APPnameValue = jsonObj.value("Appname").toString();
qDebug() << "Value for 'Appname':" << APPnameValue;
} else {
qWarning() << "'Appname' key not found in JSON.";
}
// 读取 "DeviceID" 键的值
if (jsonObj.contains("DeviceID")) {
DeviceID = jsonObj.value("DeviceID").toString();
qDebug() << "Value for 'DeviceID':" << DeviceID;
} else {
qWarning() << "'DeviceID' key not found in JSON.";
}
// 读取 "BatteryID" 键的值
if (jsonObj.contains("BatteryID")) {
BatteryID = jsonObj.value("BatteryID").toString();
qDebug() << "Value for 'BatteryID':" << BatteryID;
} else {
qWarning() << "'BatteryID' key not found in JSON.";
}
}
进阶用法
QString APPnameValue = "";
QString DeviceID = "";
QString siteCode = "";
QString equipNum = "";
QString productType = "";
QString userName = "";
QString qualityStatus = "";
QString completeQty = "";
QString testOrderNum = "";
void OnlineFrameViewModel::readJson(const QString &filePath)
{
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "Could not open file for reading:" << file.errorString();
return;
}
QJsonDocument jsonDoc = QJsonDocument::fromJson(file.readAll());
file.close();
if (jsonDoc.isNull() || !jsonDoc.isObject()) {
qWarning() << "Invalid JSON document or not an object";
return;
}
QJsonObject jsonObj = jsonDoc.object();
// 字段映射表
const QVector<QPair<QString, QString&>> fields = {
{"APPnameValue", APPnameValue},
{"DeviceID", DeviceID},
{"siteCode", siteCode},
{"equipNum", equipNum},
{"productType", productType},
{"userName", userName},
{"qualityStatus", qualityStatus},
{"completeQty", completeQty},
{"testOrderNum", testOrderNum}
};
// 处理每个字段
for (const auto& field : fields) {
const QString& key = field.first;
QString& target = field.second;
if (jsonObj.contains(key)) {
target = jsonObj.value(key).toString();
qDebug() << "Value for '" << key << "':" << target;
} else {
qWarning() << "'" << key << "' key not found in JSON.";
}
}
}