• 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
  • 相关阅读:
    MongoDB——(转)MongoDB 运维实战总结(转)
    MongoDB——4.4版本因果一致性会话
    架构——(转)用户中心 1亿数据 如何设计(转)
    MongoDB——命令备份
    JavaScript——JavaScript 弹窗
    git rebase
    shell脚本传参选项
    tftp 服务搭建
    gerrit搭建实现代码review
    Robot framework视频和教程分享
  • 原文地址:https://www.cnblogs.com/Pan-Z/p/6425121.html
Copyright © 2020-2023  润新知