qt Json 使用例子
时间: 2024-04-30 10:24:50 浏览: 11
以下是一个使用Qt C++中的QJsonDocument和QJsonObject类来解析JSON字符串的例子:
```cpp
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// JSON字符串
QString jsonString = "{\n"
" \"name\": \"John\",\n"
" \"age\": 30,\n"
" \"city\": \"New York\"\n"
"}";
// 从JSON字符串创建QJsonDocument对象
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toUtf8());
// 检查JSON是否有效
if(!jsonDocument.isNull())
{
// 检查JSON是否为对象类型
if(jsonDocument.isObject())
{
// 获取JSON对象
QJsonObject jsonObject = jsonDocument.object();
// 从JSON对象中获取值
QString name = jsonObject.value("name").toString();
int age = jsonObject.value("age").toInt();
QString city = jsonObject.value("city").toString();
qDebug() << "Name: " << name;
qDebug() << "Age: " << age;
qDebug() << "City: " << city;
}
else
{
qDebug() << "JSON格式不正确,不是一个对象!";
}
}
else
{
qDebug() << "JSON格式不正确!";
}
return a.exec();
}
```
输出结果如下:
```
Name: "John"
Age: 30
City: "New York"
```
在这个例子中,我们使用了QJsonDocument和QJsonObject类来解析JSON字符串。我们首先从JSON字符串创建了一个QJsonDocument对象,然后检查JSON是否有效。如果JSON有效,我们检查JSON是否为对象类型,并从JSON对象中获取值。最后,我们输出了获取的值。