qt怎么解析json的字段和值对?
2 个回答
void saveHashToFile(QVariantHash &data, QString wFile)
{
QJsonObject jsonObj=QJsonObject::fromVariantHash(data);
QJsonDocument jsonDoc;
jsonDoc.setObject(jsonObj);
QByteArray writeAryy = jsonDoc.toJson(QJsonDocument::Indented);
QFile file(wFile);
QFileInfo info(file);
QString path=info.absoluteDir().absolutePath();
QDir dir=info.absoluteDir();
if(dir.exists()==false)
dir.mkpath(path);
file.open (QIODevice::ReadWrite|QIODevice::Text);
file.resize(0);
file.write(writeAryy);
file.flush();
file.close();
}
QVariantHash readFromJsonFile(QString file,bool &isOK)
{
if(QFile::exists(file))
{
QFile jsonFile(file);
jsonFile.open (QIODevice::ReadOnly|QIODevice::Text);
QByteArray jsonArry=jsonFile.readAll();
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonArry, &jsonError);
jsonFile.flush();
jsonFile.close();
if(jsonError.error == QJsonParseError::NoError)
{
isOK=true;
return jsonDoc.object().toVariantHash();
}
else
{
isOK=false;
qDebug()<<"load json set file,decode json error ,file name: "<<file<<jsonError.errorString();
return QVariantHash();
}
}
else
{
isOK=false;
qDebug()<<"load json set file false ,file not exist, file name:"<<file;
return QVariantHash();
}
}