QJsonObject obj;
obj.insert("name","Ace");
obj.insert("sex","man");
obj.insert("agr","20");
QJsonObject subobj;
subobj.insert("father","Gol_D_Roger");
subobj.insert("mother","ELLien_D_Roger");
subobj.insert("brother","sabo");
QJsonArray array;
array.append("sabo");
array.append("jalen");
subobj.insert("brother",array);
subobj.insert("isalive",true);
obj.insert("family",subobj);
QJsonDocument doc(obj);
QByteArray json =doc.toJson();
QFile file("D:\\ace.json");
file.open(QIODevice::WriteOnly);
file.write(json);
file.close();
```cpp
void MainWindow::readJson()
{
QFile file("D:\\ace.json");
file.open(QIODevice::ReadOnly);
QByteArray all =file.readAll();
file.close();
QJsonDocument doc;
doc =QJsonDocument::fromJson(all);
if(doc.isObject())
{
QJsonObject obj=doc.object();
QStringList keys=obj.keys();
for(int i=0;i<keys.size();++i)
{
QString key=keys.at(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.toDouble();
}else if(value.isObject())
{
qDebug()<<key;
QJsonObject subobj= value.toObject();
QStringList subkeys =subobj.keys();
for(int k=0;k<subkeys.size();++k)
{
QJsonValue subValue =subobj.value(subkeys.at(k));
if(subValue.isString())
{
qDebug()<<" "<<subkeys.at(k)<<":"<<subValue.toString();
}else if(subValue.isArray())
{
QJsonArray array=subValue.toArray();
qDebug()<<" "<<subkeys.at(k)<<":";
for(int j=0;j<array.size();++j)
{
qDebug()<<" "<<array[j].toString();
}
}
}
}
}
}
}
|