QJson 解析

查了一堆资料,都是乱七八糟的,Qt文档里也没写清楚。总结了一下,一般有两种情况

  1. 解析对象
  2. 解析数组

对于对象:

obj.json

1
2
3
4
{
"id": "0",
"name": "obj"
}

obj.cpp

1
2
3
4
5
6
7
8
9
10
11
QFile* qFile = new QFile("obj.json");
qFile->open(QIODevice::ReadOnly | QIODevice::Text);
QString qString = qFile->readAll();
QJsonDocument qJsonDocument = QJsonDocument::fromJson(qString.toUtf8());
QJsonObject result = qJsonDocument.object();
qDebug() << result;
QJsonValue valueId = result.value("id").toString();
QJsonValue valueName = result.value("name").toString();
qDebug() << valueId;
qDebug() << valueName;
qFile->close();

result:

1
2
3
QJsonObject({"id":"0","name":"obj"})
QJsonValue(string, "0")
QJsonValue(string, "obj")

对于数组:

array.json

1
2
3
4
5
6
[
{
"id": "1",
"name": "array"
}
]

array.cpp

1
2
3
4
5
6
7
8
9
10
11
QFile* qFile = new QFile("array.json");
qFile->open(QIODevice::ReadOnly | QIODevice::Text);
QString qString = qFile->readAll();
QJsonDocument qJsonDocument = QJsonDocument::fromJson(qString.toUtf8());
QJsonObject result = qJsonDocument.array().at(0).toObject();
qDebug() << result;
QJsonValue valueId = result.value("id").toString();
QJsonValue valueName = result.value("name").toString();
qDebug() << valueId;
qDebug() << valueName;
qFile->close();

result:

1
2
3
QJsonObject({"id":"1","name":"array"})
QJsonValue(string, "1")
QJsonValue(string, "array")

代码很简单,数组取个.array().at(index).toObject(), 然后当做对象来解析