使用 QJsonDocument 處理 JSON

2021-07-30 10:52:43 字數 2539 閱讀 4469

如果你的應用僅僅需要考慮相容 qt5,其實已經有了內建的處理函式。qt5 新增加了處理 json 的類,與 xml 類庫類似,均以 qjson 開頭,在 qtcore 模組中,不需要額外引入其它模組。qt5 新增加六個相關類:

類名作用

qjsonarray

封裝 json 陣列

qjsondocument

讀寫 json 文件

qjsonobject

封裝 json 物件

qjsonobject::iterator

用於遍歷qjsonobject的 stl 風格的非 const 遍歷器

qjsonparseerror

報告 json 處理過程中出現的錯誤

qjsonvalue

封裝 json 值

我們使用下面的 json 文件,這次用qjsondocument 來解析。注意,qjsondocument要求使用 qt5,本章中所有**都必須在 qt5 環境下進行編譯執行。

qstring json(""

"}");

qjsonparseerror error;

qjsondocument jsondocument = qjsondocument::fromjson(json.toutf8(), &error);

if (error.error == qjsonparseerror::noerror)

qvariantmap nestedmap = result["indent"].tomap();

qdebug() << "length:"

<< nestedmap["length"].toint();

qdebug() << "use_space:"

<< nestedmap["use_space"].tobool();

}} else

qjsondocument::fromjson()可以由qbytearray物件構造乙個qjsondocument物件,用於我們的讀寫操作。這裡我們傳入乙個qjsonparseerror物件的指標作為第二個引數,用於獲取解析的結果。如果qjsonparseerror::error()的返回值為qjsonparseerror::noerror,說明一切正常,則繼續以qvariant的格式進行解析(由於我們知道這是乙個 json 物件,因此只判斷了isobject()。當處理未知的 json 時,或許應當將所有的情況都考慮一邊,包括isobject()、isarray()以及isempty())。

也就是說,如果需要使用qjsondocument處理 json 文件,我們只需要使用下面的**模板:

// 1. 建立 qjsonparseerror 物件,用來獲取解析結果

qjsonparseerror error;

// 2. 使用靜態函式獲取 qjsondocument 物件

qjsondocument jsondocument = qjsondocument::fromjson(json.toutf8(), &error);

// 3. 根據解析結果進行處理

if (error.error == qjsonparseerror::noerror) else

if (jsondocument.isarray())

}} else

將qvariant物件生成 json 文件也很簡單:

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())

這裡我們仍然使用的是qjsondocument,只不過這次我們需要使用qjsondocument::fromvariant()函式獲取qjsondocument物件。qjsondocument也可以以二進位制格式讀取物件,比如qjsondocument::frombinarydata()和qjsondocument::fromrawdata()函式。當我們成功獲取到qjsondocument物件之後,可以使用tojson()生成 json 文件。

以上介紹了當我們有乙個 json 文件時,如何使用qjsondocument進行處理。如果我們沒有 json 文件,那麼我們可以使用qjsondocument的setarray()和setobject()函式動態設定該物件,然後再生成對應的 json 格式文件。不過這部分需求比較罕見,因為我們直接可以從qvariant值型別獲取。

qt5 提供的 json 類庫直接支援隱式資料共享,因此我們不需要為複製的效率擔心。

本文**豆子大神的部落格:

使用GraphEdit使用

1 註冊元件。其實乙個filter就是乙個com元件,所以使用之前需要註冊,可以有兩種方法對元件進行註冊。1.直接使用命令。命令列下輸入 regsvr32 hqtlystd.ax 編譯之後你會在工程目錄下的debug中找到hqtlystd.ax,這個就是要用的filter 即可註冊成功。2.vc6....

MySQL使用學習使用 mysql學習使用

1 mysql學習 1 安裝 ubuntu下直接安裝 apt get install mysql server 2 檢查伺服器是否啟動 sudo netstat tap grep mysql,如果啟動成功,出現以下資訊 tcp00localhost.localdomain mysql listen ...

學習使用CSDN markdown使用

建立乙個自定義列表 如何建立乙個註腳 注釋也是必不可少的 katex數學公式 新的甘特圖功能,豐富你的文章 uml 圖表 flowchart流程圖 匯出與匯入 你好!這是你第一次使用markdown編輯器所展示的歡迎頁。如果你想學習如何使用markdown編輯器,可以仔細閱讀這篇文章,了解一下mar...