Qt之JSON生成與解析

2021-10-01 04:18:33 字數 1398 閱讀 6587

因為最近在使用mqtt做資料的收發用到json,linux arm中因為使用了cjson的第三方庫做了解析,比較簡單。

但是具體的在pc端使用的qt進行的客戶端的編寫,而qt是自帶json的資料解析庫的,所以,需要簡單的研究下,摘過這篇部落格,並做加入一點自己的筆記。

qt5 中包含了處理 json 的類,均以 **son 開頭(例如:**sondocument、**sonarray、**sonobject),在 qtcore 模組中,不需要額外引入其它模組。

json.org 中介紹了 json 在各種語言中的應用,在 c/c++ 中比較常用的json 庫主要有以下幾個:

jsoncpp

jsoncpp 是乙個 c++ 用來處理 json 資料的開發包。

**:cjson

cjson 是乙個超輕巧,攜帶方便,單檔案,簡單的可以作為 ansi-c 標準的 json 解析器。

**:**son

**son 是乙個基於 qt 的開發包用來將 json 資料解析成 qvariant 物件,json 的陣列將被對映為qvariantlist 例項,而其他物件對映為 qvariantmap 例項。

**:

//組成json物件

**sonobject json1;

json1.insert("name", "111");

json1.insert("pass", 222);

json1.insert("flout", 33.33);

**sondocument doc;

doc.setobject(json1);

qbytearray byte = doc.tojson(**sondocument::compact);

qdebug()例子一:

**sonobject mainwindow::qstringtojson(qstring jsonstring)

**sonobject jsonobject = jsondocument.object();

return jsonobject;}

qstring mainwindow::jsontoqstring(**sonobject jsonobject)

例子二:

//qstring轉**sonobject

**sonobject convertqstringto**sonobject(const qstring jsonstring)

**sonobject jsonobject = jsondocument.object();

return jsonobject;

}//**son轉qstring

qstring convert**sonobjecttoqstring(const **sonobject& jsonobject)

Qt解析JSON陣列

json 陣列在中括號中書寫,以逗號分隔。json 中陣列值必須是合法的 json 資料型別 字串,數字,物件,陣列,布林值或 null 比如 qt解析方式 qbytearray array sonparseerror error sondocument document sondocument f...

QT解析json檔案

include qstring filename 3.json 先判定檔案是否存在,在開啟檔案 是否正確開啟 if filename.exists if filename.open qiodevice readonly qbytearray alldata file.readall 關閉檔案file...

golang xml和json的解析與生成

golang中解析xml時我們通常會建立與之對應的結構體,一層層巢狀,完成複雜的xml解析。package main import encoding xml fmt 我們通過定義乙個結構體,來解析xml 注意,結構體中的字段必須是可匯出的 type books struct type book st...