版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a844651990/article/details/90489487
前言
Qt中对JSON支持提供了一个易于使用的c++ API来解析、修改和保存JSON数据。它还支持以二进制格式保存这些数据,这种格式是直接“mmap”的,并且访问起来非常快。
读Json数据
Json文件,1.json
{
"name": "flywm",
"age": "18",
"home": "tianjin"
}
程序:
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("D:/1.json");
if(!file.open(QIODevice::ReadOnly)) {
qDebug() << "File open failed!";
} else {
qDebug() <<"File open successfully!";
}
QJsonDocument jdc(QJsonDocument::fromJson(file.readAll()));
QJsonObject obj = jdc.object();
qDebug() << obj.value("name").toString()
<< obj.value("age").toString()
<< obj.value("home").toString();
}
写Json数据
和上面的文件内容一样。
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("D:/1.json");
if(!file.open(QIODevice::WriteOnly)) {
qDebug() << "File open failed!";
} else {
qDebug() <<"File open successfully!";
}
QJsonObject obj;
obj["age"] = "18";
obj["name"] = "flywm";
obj.insert("home", "tianjin");
QJsonDocument jdoc(obj);
file.write(jdoc.toJson());
file.flush();
}
使用QJsonArray:
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("D:/1.json");
if(!file.open(QIODevice::WriteOnly)) {
qDebug() << "File open failed!";
} else {
qDebug() <<"File open successfully!";
}
QJsonObject rootObj;
QJsonObject obj;
obj["age"] = "18";
obj["name"] = "flywm";
obj.insert("home", "tianjin");
QJsonObject obj1;
obj1["age"] = "19";
obj1["name"] = "flywm";
obj1.insert("home", "tianjin");
QJsonArray classArray;
classArray.append(obj);
classArray.append(obj1);
rootObj["class"] = classArray;
QJsonDocument jdoc(rootObj);
file.write(jdoc.toJson());
file.flush();
}
json:
{
"class": [
{
"age": "18",
"home": "tianjin",
"name": "flywm"
},
{
"age": "19",
"home": "tianjin",
"name": "flywm"
}
]
}
修改Json数据
有时候我们读出来json数据之后可能会需要修改,这里其实就是再重写一遍,关键点是file.seek(0),从头开始写,不然修改的会继续往下写造成重复。这种情况适合修改现有json数据。如果需要添加或者减少最好还是将文件清空重新写入吧。
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("D:/1.json");
if(!file.open(QIODevice::ReadWrite)) {
qDebug() << "File open failed!";
} else {
qDebug() <<"File open successfully!";
}
QJsonDocument jdc(QJsonDocument::fromJson(file.readAll()));
QJsonObject obj = jdc.object();
// 修改 age
obj["age"] = "99";
jdc.setObject(obj);
file.seek(0);
file.write(jdc.toJson());
file.flush();
}