用qt写一个解析json文件的程序
时间: 2023-12-02 13:06:14 浏览: 35
Sure, 你可以使用Qt提供的QJsonDocument类来解析JSON文件。以下是使用QJsonDocument解析JSON文件的代码示例:
```
#include <QCoreApplication>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("your_json_file.json");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Failed to open file!";
return -1;
}
QString json_str = file.readAll();
QJsonDocument json_doc = QJsonDocument::fromJson(json_str.toUtf8());
if (json_doc.isNull())
{
qDebug() << "Failed to create JSON document!";
return -1;
}
if (!json_doc.isObject())
{
qDebug() << "JSON is not an object!";
return -1;
}
QJsonObject json_obj = json_doc.object();
// Use the json_obj to access the JSON object's properties and values
return a.exec();
}
```
Hope this helps!