一、思路
QT中JSON格式的创建和解析涉及到QJsonObject、QJsonArray、QJsonDocument这三个,分别对应json对象、json数组以及编码转换,帮助文件查阅这三个类即可知道如何使用。
二、例子
#include <QCoreApplication>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>
#include <QFile>
void writeJson()
{
QJsonObject rootObj;
//1.插入name字段
rootObj.insert("name", "China");
//2.插入info字段
QJsonObject infoObj;
infoObj.insert("capital", "beijing");
infoObj.insert("asian", true);
infoObj.insert("founded", 1949);
rootObj.insert("info", infoObj);
//3.插入provinces字段
QJsonArray provincesArray;
QJsonObject provinceSdObj;
provinceSdObj.insert("name", "shandong");
provinceSdObj.insert("capital", "jinan");
QJsonObject provinceZjObj;
provinceZjObj.insert("name", "zhejiang");
provinceZjObj.insert("capital", "hangzhou");
provincesArray.append(provinceSdObj);
provincesArray.append(provinceZjObj);
rootObj.insert("provinces", provincesArray);
//4.将rootObj转换为JSON字符串
QJsonDocument doc(rootObj);
QByteArray json = doc.toJson();
//5.1打印输出
qDebug() << QString(json).toUtf8().data();
//5.2将JSON字符串写入到文件
QFile file("C:\\Users\\EDY\\Desktop\\QTtest\\JSON\\china.json");
file.open(QFile::WriteOnly);
file.write(json);
file.close();
}
void fromJson()
{
//1.读取文件
QFile file("C:\\Users\\EDY\\Desktop\\QTtest\\JSON\\china.json");
file.open(QFile::ReadOnly);
QByteArray json = file.readAll();
file.close();
QJsonDocument doc = QJsonDocument::fromJson(json);
if(!doc.isObject())
{
qDebug() << "Not an object!";
return;
}
//2.开始解析
QJsonObject obj = doc.object();
QStringList keys = obj.keys();
for(int i=0;i<keys.size();i++)
{
//获取key-value
QString key = keys[i];
QJsonValue value = obj.value(key);
if(value.isBool())
{
qDebug() << key << ":" <<value.toBool();
}
else if(value.isString())
{
qDebug() << key << ":" <<value.toString();
}
else if(value.isDouble())
{
qDebug() << key << ":" <<value.toInt();
}
else if(value.isObject())
{
qDebug() << key << ":";
QJsonObject infoObj = value.toObject();
QString capital = infoObj["capital"].toString();
bool asian = infoObj["asian"].toBool();
int founded = infoObj["founded"].toInt();
qDebug() << " " << "capital" << ":" << capital;
qDebug() << " " << "asian" << ":" << asian;
qDebug() << " " << "founded" << ":" << founded;
}
else if(value.isArray())
{
qDebug() << key;
QJsonArray provinceArray = value.toArray();
for(int i=0;i<provinceArray.size();i++)
{
QJsonObject provinceObj = provinceArray[i].toObject();
QString name = provinceObj["name"].toString();
QString capital = provinceObj["capital"].toString();
qDebug() << " " << "name" << ":" << name << ", capital" << ":" << capital;
}
}
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// writeJson();
fromJson();
return a.exec();
}
上述例子包含json文件的构建与解析。