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",42);
   json.insert("height",23);

   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 :  23
widght :  42

 

posted @ 2017-02-21 17:15  暗夜影  阅读(6463)  评论(0编辑  收藏  举报