(1)JSON文件(config.json)
-
{
-
"autor":
"yudabo",
-
"staff":[
-
{
"name":
"于大博1"},
-
{
"name":
"于大博2"},
-
{
"name":
"于大博3"},
-
{
"name":
"于大博4"},
-
{
"name":
"于大博5"},
-
{
"name":
"于大博6"},
-
{
"name":
"于大博7"},
-
{
"name":
"于大博8"},
-
{
"name":
"于大博9"},
-
{
"name":
"于大博10"}
-
],
-
"data": {
"name":
"yudabo" }
-
}
(2)解析文件
-
QFile file("config.json");
-
file.open(QIODevice: :ReadOnly | QIODevice: :Text);
-
QString
value = file.readAll();
-
file.close();
-
-
QJsonParseError parseJsonErr;
-
QJsonDocument document = QJsonDocument: :fromJson(
value.toUtf8(), &parseJsonErr);
-
if (! (parseJsonErr.error == QJsonParseError: :NoError)) {
-
QMessageBox: :about(NULL,
"提示",
"配置文件错误!");
-
return;
-
}
-
-
QJsonObject jsonObject = document.
object();
-
/*
-
// autor字段
-
qDebug()<< "jsonObject[autor]==" << jsonObject["autor"].toString();
-
*/
-
// staff字段
-
if (jsonObject.contains(QStringLiteral(
"staff"))) {
-
QJsonValue arrayValue = jsonObject.
value(QStringLiteral(
"staff"));
-
if (arrayValue.isArray()) {
-
QJsonArray array = arrayValue.toArray();
-
for (
int i =
0; i < array.size(); i++) {
-
QJsonValue nameArray = array.at(i);
-
QJsonObject key = nameArray.toObject();
-
qDebug() <<
"key[name]==" << key[
"name"].toString();
-
}
-
}
-
}
-
// data字段
-
QJsonValue jsonDataValue = jsonObject.
value(QStringLiteral(
"data"));
-
QJsonObject jsonData = jsonDataValue.toObject();
-
qDebug()<<
"jsonData [name]==" << jsonData [
"name"].toString();
补充json文件写入
在这里插入代码片`
QJsonObject obj;
QJsonObject sub;
sub.insert("ip",QJsonValue("192.168.0.1"));
sub.insert("port",QJsonValue("8080"));
obj.insert("server",QJsonValue(sub));
//内存中的数据写到文件
QJsonDocument doc(obj);
//将json对象转换成字符串
QByteArray data=doc.toJson();
QFile file("temo.json");
file.open(QIODevice::WriteOnly);
file.write(data);
file.close();