之前的文章
JSON介绍
使用Qt读写JSON文件(一)——简单的写入文件
之前介绍了简单的示例,这次我们进行JSON文件的解析。
在你的桌面新建文件命名为test.json,内容填写如下:
{
"postsNum" : 2,
"posts" : [
{
"postID" : 10086,
"postTitle" : "hello",
"postContent" : "你好啊"
},
{
"postID" : 10010,
"postTitle" : "hi",
"postContent" : "大家好"
}
]
}
从JSON定义来看,这是一个包含有两个键值对的对象,其中一个键值对的名字是"postsNum",值是一个数字,另一键值对的名字是"posts",值是一个数组。这个数组由两个对象组成,每个对象由三个相同的键值对组成,第一个键值对名字为"postID" ,值为数字;第二个键值对名字为 “postTitle” ,值为字符串 “hello”;第三个键值对名字为 “postContent” ,值为字符串。实际上,数组中的对象描述了一个简单的帖子的数据结构,这个帖子有postID、postTitle、postContent组成。
接下来我们使用Qt Creator新建一个Qt Console Application项目,名称和位置可以随意。
修改默认生成的main.cpp中的代码如下所示:
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>
#include <QSysInfo>
#include <cstdlib>
#include <iostream>
using std::cout;
int main