您的位置:首页 > 编程语言 > Qt开发

qt5 解析Json文件

2015-12-06 11:00 441 查看
/* test.json */
{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}

void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;

/* incase of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();

/* incase of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}

http://stackoverflow.com/questions/15893040/how-to-create-read-write-json-files-in-qt5
摘于上面的链接,大部分已经能用了。

我来说下其他情况:
{"file":"book.png","frames":{
"v1":{"x":1,"y":91,"w":68,"h":87,"offX":0,"offY":0,"sourceW":68,"sourceH":87},
"v2":{"x":1,"y":1,"w":68,"h":88,"offX":0,"offY":0,"sourceW":68,"sourceH":88},
"v3":{"x":209,"y":1,"w":66,"h":87,"offX":0,"offY":0,"sourceW":66,"sourceH":87},
"v4":{"x":71,"y":1,"w":67,"h":88,"offX":0,"offY":0,"sourceW":67,"sourceH":88},
"v5":{"x":71,"y":91,"w":67,"h":88,"offX":0,"offY":0,"sourceW":67,"sourceH":88},
"v6":{"x":140,"y":1,"w":67,"h":87,"offX":0,"offY":0,"sourceW":67,"sourceH":87},
"v7":{"x":140,"y":90,"w":67,"h":87,"offX":0,"offY":0,"sourceW":67,"sourceH":87}}}
像这样的json,想要得到frames里所有的内容,因为它不是一个数组,所以要用迭代器来访问,类似这样的代码:

bool MainWindow::parseJsonFile(){

QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject rootObject = d.object();
QJsonValue pngNameJsonValue = rootObject.value(QString("file"));
qWarning() << pngNameJsonValue.toString();

QJsonValue framesJsonValue = rootObject.value(QString("frames"));
qWarning() << framesJsonValue;

QStringList imgNameList = framesJsonValue.toObject().keys();
QJsonObject frameObject = framesJsonValue.toObject();
int index = 0;
for(auto beginItr = frameObject.begin(); beginItr != frameObject.end(); ++beginItr){

QJsonValue eachImageJsonValue = *beginItr;

QJsonObject eachImageJsonObject = eachImageJsonValue.toObject();

//eachImageJsonObject["x"], eachImageJsonObject["y"] ...
}
return true;
}

还有QJsonValue里用.keys()得到所有的key,然后就可以通过["key"] 来访问了。

http://www.waitingfy.com/archives/1775
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: