【Qt筆記】使用 QJsonDocument 處理 JSON

上一章咱們瞭解瞭如何使用 QJson 處理 JSON 文檔。QJson 是一個基於 Qt 的第三方庫,適用於 Qt4 和 Qt5 兩個版本。不過,若是你的應用僅僅須要考慮兼容 Qt5,其實已經有了內置的處理函數。Qt5 新增長了處理 JSON 的類,與 XML 類庫相似,均以 QJson 開頭,在 QtCore 模塊中,不須要額外引入其它模塊。Qt5 新增長六個相關類:python

QJsonArray 封裝 JSON 數組
QJsonDocument 讀寫 JSON 文檔
QJsonObject 封裝 JSON 對象
QJsonObject::iterator 用於遍歷QJsonObject的 STL 風格的非 const 遍歷器
QJsonParseError 報告 JSON 處理過程當中出現的錯誤
QJsonValue 封裝 JSON 值

 

咱們仍是使用前一章的 JSON 文檔,此次換用QJsonDocument 來解析。注意,QJsonDocument要求使用 Qt5,本章中全部代碼都必須在 Qt5 環境下進行編譯運行。c++

QString json("{"
        "\"encoding\" : \"UTF-8\","
        "\"plug-ins\" : ["
        "\"python\","
        "\"c++\","
        "\"ruby\""
        "],"
        "\"indent\" : { \"length\" : 3, \"use_space\" : true }"
        "}");
QJsonParseError error;
QJsonDocument jsonDocument = QJsonDocument::fromJson(json.toUtf8(), &error);
if (error.error == QJsonParseError::NoError) {
    if (jsonDocument.isObject()) {
        QVariantMap result = jsonDocument.toVariant().toMap();
        qDebug() << "encoding:" << result["encoding"].toString();
        qDebug() << "plugins:";

        foreach (QVariant plugin, result["plug-ins"].toList()) {
            qDebug() << "\t-" << plugin.toString();
        }

        QVariantMap nestedMap = result["indent"].toMap();
        qDebug() << "length:" << nestedMap["length"].toInt();
        qDebug() << "use_space:" << nestedMap["use_space"].toBool();
    }
} else {
    qFatal(error.errorString().toUtf8().constData());
    exit(1);
}

這段代碼與前面的幾乎相同。QJsonDocument::fromJson()能夠由QByteArray對象構造一個QJsonDocument對象,用於咱們的讀寫操做。這裏咱們傳入一個QJsonParseError對象的指針做爲第二個參數,用於獲取解析的結果。若是QJsonParseError::error()的返回值爲QJsonParseError::NoError,說明一切正常,則繼續以QVariant的格式進行解析(因爲咱們知道這是一個 JSON 對象,所以只判斷了isObject()。當處理未知的 JSON 時,或許應當將全部的狀況都考慮一邊,包括isObject()isArray()以及isEmpty())。json

也就是說,若是須要使用QJsonDocument處理 JSON 文檔,咱們只須要使用下面的代碼模板:數組

// 1. 建立 QJsonParseError 對象,用來獲取解析結果
QJsonParseError error;
// 2. 使用靜態函數獲取 QJsonDocument 對象
QJsonDocument jsonDocument = QJsonDocument::fromJson(json.toUtf8(), &error);
// 3. 根據解析結果進行處理
if (error.error == QJsonParseError::NoError) {
    if (!(jsonDocument.isNull() || jsonDocument.isEmpty())) {
        if (jsonDocument.isObject()) {
            // ...
        } else if (jsonDocument.isArray()) {
            // ...
        }
    }
} else {
    // 檢查錯誤類型
}

QVariant對象生成 JSON 文檔也很簡單:ruby

QVariantList people;

QVariantMap bob;
bob.insert("Name", "Bob");
bob.insert("Phonenumber", 123);

QVariantMap alice;
alice.insert("Name", "Alice");
alice.insert("Phonenumber", 321);

people << bob << alice;

QJsonDocument jsonDocument = QJsonDocument::fromVariant(people);
if (!jsonDocument.isNull()) {
    qDebug() << jsonDocument.toJson();
}

這裏咱們仍然使用的是QJsonDocument,只不過此次咱們須要使用QJsonDocument::fromVariant()函數獲取QJsonDocument對象。QJsonDocument也能夠以二進制格式讀取對象,好比QJsonDocument::fromBinaryData()QJsonDocument::fromRawData()函數。當咱們成功獲取到QJsonDocument對象以後,可使用toJson()生成 JSON 文檔。函數

以上介紹了當咱們有一個 JSON 文檔時,如何使用QJsonDocument進行處理。若是咱們沒有 JSON 文檔,那麼咱們可使用QJsonDocumentsetArray()setObject()函數動態設置該對象,而後再生成對應的 JSON 格式文檔。不過這部分需求比較罕見,由於咱們直接能夠從QVariant值類型獲取。spa

Qt5 提供的 JSON 類庫直接支持隱式數據共享,所以咱們不須要爲複製的效率擔憂。指針

相關文章
相關標籤/搜索