JSON - Qt 对 JSON的处理

1.关于JSON的介绍参考www.json.org

Qt提供处理JSON数据的支持。
QJSonObject类用于封装JSON object;
QJsonDocument类提供读写JSON文档的方法;
QJsonParseError类用于在JSON解析过程中报告错误。
上述三个类均是从Qt 5.0开始支持。

示例:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonParseError>
#include<QDebug> MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this); QJsonObject json;
json.insert("Type",QString("Rectangle"));
json.insert("widght",);
json.insert("height",); QJsonDocument document;
document.setObject(json);
QByteArray byteArray = document.toJson(QJsonDocument::Compact);
qDebug()<<byteArray; QJsonParseError jsonError;
QJsonDocument parseDoc = QJsonDocument::fromJson(byteArray,&jsonError);
if(jsonError.error == QJsonParseError::NoError)
{
if(parseDoc.isObject())
{
QJsonObject jsonObj = parseDoc.object();
if(jsonObj.contains("Type"))
{
QJsonValue typeValue = jsonObj.take("Type");
if(typeValue.isString())
{
QString strValue= typeValue.toString();
qDebug()<<"Type : "<<strValue;
}
}
if(jsonObj.contains("height"))
{
QJsonValue heightValue = jsonObj.take("height");
if(heightValue.isDouble())
{
int iValue = heightValue.toVariant().toInt();
qDebug()<<"height : "<<iValue;
}
}
if(jsonObj.contains("widght"))
{
QJsonValue widghtValue = jsonObj.take("widght");
if(widghtValue.isDouble())
{
int iValue =widghtValue.toVariant().toInt();
qDebug()<<"widght : "<<iValue;
}
}
}
}
} MainWindow::~MainWindow()
{
delete ui;
}

结果如下:

"{\"Type\":\"Rectangle\",\"height\":23,\"widght\":42}"
Type : "Rectangle"
height :
widght :
上一篇:ARM Cortex-M instructions


下一篇:.NET应用架构设计—重新认识分层架构(现代企业级应用分层架构核心设计要素)