json是一种轻量级的数据交换格式。
下面我们用qt实现JSON
MyWidget.cpp
#include "MyWidget.h"
#include <QApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QCryptographicHash>
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
QJsonObject obj;
QByteArray md5 = QCryptographicHash::hash(QByteArray("minxminx"),QCryptographicHash::Md5);
obj.insert("username",QString("minxminx1"));
obj.insert("password",QString(md5.toHex()));
obj.insert("male",true);
obj.insert("age",36);
QJsonDocument doc(obj);
//没有换行的
QByteArray json = doc.toJson(QJsonDocument::Compact);
//有换的
//QByteArray json = doc.toJson(QJsonDocument::Indented);
qDebug() << json;
QJsonDocument doc2 = QJsonDocument::fromJson(json);
QJsonObject obj2 = doc2.object();
if(obj2.value("username").toString() == "minxminx1")
{
qDebug() << "yes";
}
}
int main(int argc,char** argv)
{
QApplication app(argc,argv);
MyWidget w;
w.show();
return app.exec();
}
补充一下头文件和项目文件:
T17Json.pro
HEADERS += \
MyWidget.h
SOURCES += \
MyWidget.cpp
QT +=widgets gui
MyWidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
signals:
public slots:
};
#endif // MYWIDGET_H
程序输出
"{\"age\":36,\"male\":true,\"password\":\"e953e00e4ed190e46daf07f9f3da2d52\",\"username\":\"minxminx1\"}"
yes
如果是
QJsonDocument::Indented
模式的话:
"{\n \"age\": 36,\n \"male\": true,\n \"password\": \"e953e00e4ed190e46daf07f9f3da2d52\",\n \"username\": \"minxminx1\"\n}\n"
就会有换行。