JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,基於JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一個子集。 JSON採用徹底獨立於語言的文本格式,使用了類C語言家族的習慣(包括C、C++、C#、Java、JavaScript、Perl、Python等)。web
JSON語法是JavaScript對象表示法語法的子集,語法規則以下:json
A、數據在key/value
對中數組
B、數據由逗號分隔測試
C、花括號保存對象code
D、方括號保存數組對象
JSON 數據的書寫格式是:key/value。ip
名稱/值對包括字段名稱(在雙引號中),後面寫一個冒號,而後是值:文檔
"firstName" : "John"
字符串
JSON值類型:get
數字(整數或浮點數)
字符串(在雙引號中)
邏輯值(true或false)
數組(在方括號中)
對象(在花括號中)
null
JSON對象在花括號中書寫:
對象能夠包含多個key/value對:
{ "firstName":"John" , "lastName":"Doe" }
JSON數組在方括號中書寫:
數組可包含多個對象:
{ "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" }] }
使用到的類:
QJsonArray | 封裝 JSON 數組 |
---|---|
QJsonDocument | 讀寫 JSON 文檔 |
QJsonObject | 封裝 JSON 對象 |
QJsonObject::iterator | 用於遍歷QJsonObject的STL風格的非const遍歷器 |
QJsonParseError | 報告 JSON 處理過程當中出現的錯誤 |
QJsonValue | 封裝 JSON 值 |
Json文件地址:http://pvp.qq.com/web201605/js/herolist.json
下載後的JSON文件(消減版)
[{ "ename": 105, "cname": "廉頗", "title": "正義爆轟", "new_type": 0, "hero_type": 3, "skin_name": "正義爆轟|地獄巖魂" }, { "ename": 106, "cname": "小喬", "title": "戀之微風", "new_type": 0, "hero_type": 2, "skin_name": "戀之微風|萬聖前夜|天鵝之夢|純白花嫁|繽紛獨角獸" }]
#include <QCoreApplication> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QJsonParseError> #include <QJsonValue> #include <QStringList> #include <QFile> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QJsonParseError jsonError; QByteArray Json; QFile file("herolist.json"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << file.errorString(); } else { qDebug() << "open sucess !"; Json = file.readAll(); } QString str = str.fromLocal8Bit(Json.data()); //qDebug()<<Json.data(); QJsonDocument doucment = QJsonDocument::fromJson(Json, &jsonError); if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)) { if (doucment.isArray()) { qDebug()<<"Json數組讀取"; QJsonArray array = doucment.array(); /*獲取QJsonArray對象*/ int nSize = array.size(); /*Json數組大小*/ for (int i = 0; i < nSize; ++i) { // 遍歷數組 QJsonValue value = array.at(i); QJsonObject key = value.toObject(); /*獲取數組對象*/ qDebug() << "ename==" << key["ename"].toInt(); qDebug() << "cname==" << key["cname"].toString(); qDebug() << "title==" << key["title"].toString(); qDebug() << "new_type==" << key["new_type"].toInt(); qDebug() << "hero_type==" << key["hero_type"].toInt(); qDebug() << "skin_name==" << key["skin_name"].toString(); qDebug() << "****************************************************************"; } } } return a.exec(); }