在Qt中QVariantList 使用起来很方便,如果涉及到数据的传输,需要将QVariantList 数据转换为JsonArray字符串,这个转换Qt已经实现好了,只需要调用接口就可以完成转换,代码如下:
main.cpp
#include <QCoreApplication> #include <QJsonArray> #include <QJsonDocument> #include <QJsonValue> #include <QJsonObject> #include <QVariantMap> #include <QVariantList> #include <QDebug> 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<<tmpvm; } qDebug()<<"qvarList: "<<QVarList; //QVariantList转为Jsonarray字符串 QJsonArray jsonArray = QJsonArray::fromVariantList(QVarList); QJsonDocument jsonDoc(jsonArray); qDebug()<<"------------------------------QVariantList to json-------------------------------"; qDebug() << jsonDoc.toJson(); //Jsonarray字符串转为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: "<<json.array().toVariantList();; return a.exec(); }
执行结果:
为了方便看,手动把执行结果的格式调整了下,加了换行。
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")))) )