jinqiang's online space

QJson 解析

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

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

对于对象:

obj.json

{
  "id": "0",
  "name": "obj"
}

obj.cpp

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:

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

对于数组:

array.json

[
    {
        "id": "1",
        "name": "array"
    }
]

array.cpp

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:

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

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