如何進(jìn)行QJsonArray字符串與QVariantList 對(duì)象相互轉(zhuǎn)換,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
創(chuàng)新互聯(lián)專業(yè)IDC數(shù)據(jù)服務(wù)器托管提供商,專業(yè)提供成都服務(wù)器托管,服務(wù)器租用,成都服務(wù)器托管,成都服務(wù)器托管,成都多線服務(wù)器托管等服務(wù)器托管服務(wù)。
在Qt中QVariantList 使用起來很方便,如果涉及到數(shù)據(jù)的傳輸,需要將QVariantList 數(shù)據(jù)轉(zhuǎn)換為JsonArray字符串,這個(gè)轉(zhuǎn)換Qt已經(jīng)實(shí)現(xiàn)好了,只需要調(diào)用接口就可以完成轉(zhuǎn)換,代碼如下:
main.cpp
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVariantList QVarList;
QVariantMap tmpvm;
for ( int i = 0; i < 3; i ++ )
{
tmpvm.clear();
tmpvm["name"] = QString("Test%1").arg(i);
tmpvm["no"] = QString::number(i);
QVarList<
}
qDebug()<<"qvarList: "<
//QVariantList轉(zhuǎn)為Jsonarray字符串
QJsonArray jsonArray = QJsonArray::fromVariantList(QVarList);
QJsonDocument jsonDoc(jsonArray);
qDebug()<<"------------------------------QVariantList to json-------------------------------";
qDebug() << jsonDoc.toJson();
//Jsonarray字符串轉(zhuǎn)為QVariantList
QString str = "[{\"no\": \"1\", \"name\": \"Jack\"},{\"no\": \"2\", \"name\": \"Tom\"},{\"no\": \"3\", \"name\": \"Stans\"}]";
QJsonDocument json = QJsonDocument::fromJson(str.toLatin1());
qDebug()<<"------------------------------json to QVariantList-------------------------------";
qDebug()<<"qvarList: "<
return a.exec();
}
執(zhí)行結(jié)果:
為了查看方便,下面的結(jié)果手動(dòng)調(diào)整了下格式。
qvarList:
(
QVariant(QVariantMap, QMap(("name", QVariant(QString, "Test0"))("no", QVariant(QString, "0")))),
QVariant(QVariantMap, QMap(("name", QVariant(QString, "Test1"))("no", QVariant(QString, "1")))),
QVariant(QVariantMap, QMap(("name", QVariant(QString, "Test2"))("no", QVariant(QString, "2"))))
)
------------------------------QVariantList to json-------------------------------
"[
{ "name": "Test0", "no": "0" },
{ "name": "Test1", "no": "1" },
{ "name": "Test2", "no": "2" }
]"
------------------------------json to QVariantList-------------------------------
qvarList:
(
QVariant(QVariantMap, QMap(("name", QVariant(QString, "Jack"))("no", QVariant(QString, "1")))),
QVariant(QVariantMap, QMap(("name", QVariant(QString, "Tom"))("no", QVariant(QString, "2")))),
QVariant(QVariantMap, QMap(("name", QVariant(QString, "Stans"))("no", QVariant(QString, "3"))))
)
?
看完上述內(nèi)容,你們掌握如何進(jìn)行QJsonArray字符串與QVariantList 對(duì)象相互轉(zhuǎn)換的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!