2014年02月24日 星期一 09:21
与时俱进的Qt从5.0版本开始支持JSON格式数据的编码和解码,从此使用Qt编写各种Web Service的客户端无需再引入第三方的JSON库了。从我的简单实践来看,Qt的JSON API比较清晰易懂,但相对于cxxtools等来说,并不是特别简洁。
Qt provides support for dealing with JSON data. JSON is a format to encode object data derived from Javascript, but now widely used as a data exchange format on the internet.
The JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data. It also contains support for saving this data in a binary format that is directly "mmap"-able and very fast to access.
代码示例如下:
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonObject>
#include <QDebug>
#include <QString>
#include <QByteArray>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray jsonstr;
jsonstr+="[{\"name\":\"mengguang\",\"age\":30},";
jsonstr+="{\"name\":\"mengkang\",\"age\":32}]";
qDebug() << jsonstr;
auto json=QJsonDocument::fromJson(jsonstr);
qDebug() << json.isNull();
qDebug() << json.isArray();
auto ary=json.array();
for(auto friends : ary) {
qDebug() << friends.toObject()["name"].toString();
qDebug() << friends.toObject()["age"].toInt();
}
QJsonObject obj;
obj.insert("name",QJsonValue(QString("menghui")));
obj.insert("age",QJsonValue(34));
ary.insert(2,obj);
QJsonDocument jo(ary);
qDebug() << jo.toJson() << endl;
return a.exec();
}
以上代码使用了C++11的新特性,编译时需要在qt的project文件中增加CONFIG += c++11选项。
参考资料:
Zeuux © 2025
京ICP备05028076号