如何在Qt5中创建/读取/写入JSon文件
Qt5有一个新的JSon解析器,我想使用它。问题在于,对于函数在外行术语中的作用以及如何编写代码尚不清楚。那或者我可能读错了。
我想知道在Qt5中创建Json文件的代码以及“封装”的含义。
回答:
/* test.json */{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}
void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;
/* in case of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();
/* in case of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) "QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
将json分配给字符串,如下所示,并使用readJson()
前面显示的功能:
val = ' {
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}';
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) "QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
以上是 如何在Qt5中创建/读取/写入JSon文件 的全部内容, 来源链接: utcz.com/qa/430112.html