#include <QCoreApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QFile>
#include <QDateTime>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("F:/1.json");
if (file.open(QFile::ReadWrite))
{
QByteArray data=file.readAll();
file.resize(0);//clear
QJsonParseError jsError;
QJsonDocument jsDoc(QJsonDocument::fromJson(data,&jsError));
QJsonObject rootObj=jsDoc.object();
QJsonObject subObj;//Map key:value
subObj.insert("Name","Tom");
subObj.insert("Age",18);
subObj.insert("Birth",QDateTime::currentDateTime().toString());
rootObj.insert("Tom",subObj);
QJsonArray subArr;//List value
subArr.append("Jerry");
subArr.append(18);
subArr.append(QDateTime::currentDateTime().toString());
rootObj.insert("Jerry",subArr);
jsDoc.setObject(rootObj);
file.write(jsDoc.toJson());
file.close();
}
return a.exec();
}
初始文件:
{
"Conan": {
"Age": 10,
"Birth": "周四 五月 16 09:43:58 2019",
"Name": "Conan"
},
"Pika": {
"Age": 12,
"Birth": "周四 五月 16 09:43:58 2019",
"Name": "Pika"
}
}
修改后:
{
"Conan": {
"Age": 10,
"Birth": "周四 五月 16 09:43:58 2019",
"Name": "Conan"
},
"Jerry": [
"Jerry",
18,
"周四 五月 16 09:49:46 2019"
],
"Pika": {
"Age": 12,
"Birth": "周四 五月 16 09:43:58 2019",
"Name": "Pika"
},
"Tom": {
"Age": 18,
"Birth": "周四 五月 16 09:49:46 2019",
"Name": "Tom"
}
}
Object默认字典序,Array按添加顺序;
Object包含(key,value),Array包含(value);
评论区