Qt json 格式读写
时间: 2023-05-11 17:02:27 浏览: 73
可以使用 Qt 的 QJsonDocument 类来读写 JSON 格式的数据。具体的代码实现可以参考以下示例:
// 读取 JSON 格式的数据
QFile file("data.json");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open file!";
return;
}
QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
file.close();
if (doc.isNull()) {
qDebug() << "Failed to parse JSON data!";
return;
}
QJsonObject obj = doc.object();
QString name = obj["name"].toString();
int age = obj["age"].toInt();
// 写入 JSON 格式的数据
QJsonObject obj;
obj["name"] = "John";
obj["age"] = 30;
QJsonDocument doc(obj);
QFile file("data.json");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Failed to open file!";
return;
}
file.write(doc.toJson());
file.close();