json
理论
什么是JSON?
规则
被大括号包括的是JSON对象,被中括号包括的是JSON数组.
JSON数组JSON对象
实验
构建JSON
用代码实现如下json内容:
//构建JSON
void WirteJson()
{QJsonObject rootObject;//1.插入name字段rootObject.insert("name","china");//2.插入info字段QJsonObject infoObj;infoObj.insert("capital","beijing");infoObj.insert("asian",true);infoObj.insert("founded",1949);rootObject.insert("info",infoObj);//3.插入省份字段QJsonObject provinsSD;provinsSD.insert("name","shandong");provinsSD.insert("capital","jinan");QJsonObject provinsZJ;provinsZJ.insert("name","zhejiang");provinsZJ.insert("capital","hangzhou");QJsonArray provinArray;provinArray.append(provinsSD);provinArray.append(provinsZJ);rootObject.insert("provinces",provinArray);//4.将rootObj转换为json字符串QJsonDocument doc(rootObject);QByteArray json=doc.toJson();//5.打印输出qDebug()<<QString(json).toUtf8().data();//6.将json字符串写入到文件QFile file("D:\\QTproject\\JSON.json");file.open(QFile::WriteOnly);file.write(json);file.close();
}
解析JSON
//解析json字符串
void JsonFrom()
{//1.读取文件QFile file("D:\\QTproject\\JSON.json");file.open(QFile::ReadOnly);QByteArray json=file.readAll();file.close();//获取一下json源QJsonDocument doc=QJsonDocument::fromJson(json);if(!doc.isObject()){qDebug()<<"not is a JSONObject!";return;}//name字段QJsonObject obj=doc.object();QStringList Keys=obj.keys();for(int i=0;i<Keys.size();i++){//获取key-valueQString 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();}//info字段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;qDebug()<<"capital"<< " : "<<capital;}}}
}