头文件
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
jsonObjectToMap
将Json对象转换成map
QVariantMap MainWindow:: jsonObjectToMap(const QJsonObject &jsonObject)
{
QVariantMap map;
for (const QString &key : jsonObject.keys()) {
QJsonValue value = jsonObject[key];
if (value.isString()) {
map[key] = value.toString();
} else if (value.isDouble()) {
map[key] = value.toDouble();
} else if (value.isBool()) {
map[key] = value.toBool();
} else if (value.isArray()) {
QJsonArray array = value.toArray();
QVariantList list;
for (int i = 0; i< array.size(); ++i) {
list.append(array[i].toVariant());
}
map[key] = list;
} else if (value.isObject()) {
map[key] = jsonObjectToMap(value.toObject());
}
}
return map;
}
parseJson
将Json文件转换成Json对象,再转换成map文章来源:https://www.toymoban.com/news/detail-823141.html
void MainWindow::parserJson()
{
QFile file("/home/zyt/mysettings/test.json");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qWarning() << "Failed to open file:"<< file.errorString();
return ;
}
// 读取 JSON 文件内容
QByteArray jsonData = file.readAll();
file.close();
// QByteArray jsonData = R"({"name":"John","age":30,"city":"New York","isMarried":true,"hobbies":["reading","traveling"],"address":{"street":"123 Main St","zip":12345}})";
QJsonParseError error;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &error);
if (error.error != QJsonParseError::NoError) {
qWarning() << "JSON parse error:"<< error.errorString();
return ;
}
QJsonObject jsonObject = jsonDoc.object();
QVariantMap map = jsonObjectToMap(jsonObject);
// 使用 QVariantMap
for (const QString &key : map.keys()) {
qDebug()<< key << ":"<< map[key];
}
}
结果
{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}
文章来源地址https://www.toymoban.com/news/detail-823141.html
到了这里,关于QT解析json数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!