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(); }