相关的类
QJsonObject,顾名思义,就是Json对象
QJsonArray,Json数组
QJsonDocument,用于和QByteArray相互转换;
QJsonValue,可以从QJsonObject中去key拿到对应的value,类型就是QJsonValue,可以转成实际的类型,如:QString,QJsonObject,QByteArray等;
上述说明均是来自于Qt官方文档,官方文档中有详细的API描述,也可以在Qt Creator查看类的声明;
Demo
从一个文件中读取一个嵌套的json字符串,然后递归的读取value,并打印出来
test.json
基本的json格式如下
{
"name":"root",
"children":[]
}
在上面的基本格式下嵌套多次,得到一个json文件
{
"name":"root",
"children":[
{
"name":"A",
"children":[
{
"name":"A1",
"children":[
{
"name":"A11"
},
{
"name":"A12"
},
{
"name":"A13"
}
]
},
{
"name":"A2",
"children":[
{
"name":"A21"
},
{
"name":"A22"
}
]
},
{
"name":"A3",
"children":[
{
"name":"A31"
},
{
"name":"A32"
},
{
"name":"A33"
}
]
},
{
"name":"A4",
"children":[
{
"name":"A41"
}
]
}
]
},
{
"name":"B",
"children":[
{
"name":"B1",
"children":[
{
"name":"B11"
},
{
"name":"B12"
}
]
}
]
}
]
}
解析代码
#include <QCoreApplication>
#include <QFile>
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonValue>
void readJson(QJsonObject x)
{
//递归终止条件
if(x.value("children").toArray().count() <= 0)
{
return;
}
else
{
QJsonArray qQJsonArray = x.value("children").toArray();
//遍历JsonArray
for(int i = 0; i < qQJsonArray.count(); i++)
{
QJsonObject qJsonObject = qQJsonArray.at(i).toObject();
qDebug() << qJsonObject.value("name").toString();
readJson(qJsonObject);
}
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("C:/Users/xxx/Desktop/test.json");
file.open(QIODevice::ReadOnly);
QByteArray temp = file.readAll();
file.close();
//qDebug()<<temp;
QJsonDocument qJsonDocument = QJsonDocument::fromJson(temp);
QJsonObject qJsonObject = qJsonDocument.object();
qDebug()<<qJsonObject.value("children").toArray().count();
readJson(qJsonObject);
return a.exec();
}