QT開發(六十二)———QT5解析Json文件

QT開發(六十二)———QT5解析Json文件

1、QT5 Json簡介

    QT4中使用第三方庫QJson解析JSON文件。編程

    QT5新增長了處理JSON的類,類均以QJson開頭,包含在QtCore模塊中QT5新增長六個相關類:json

QJsonArraywindows

封裝 JSON 數組數組

QJsonDocumentapp

讀寫 JSON 文檔ide

QJsonObject函數

封裝 JSON 對象編碼

QJsonObject::iteratorspa

用於遍歷QJsonObject的STL風格的非const遍歷器orm

QJsonParseError

報告 JSON 處理過程當中出現的錯誤

QJsonValue

封裝 JSON 值

2、QJsonDocument

1QJsonDocument簡介

    QJsonDocument提供了讀寫Json文檔的方法。

    QJsonDocument是一個包含了完整JSON文檔的類,支持以UTF-8編碼的文本和QT自身的二進制格式來讀寫JSON文檔。

    JSON文檔可使用QJsonDocument::fromJson()將基於JSON文檔的文本形式轉換爲QJsonDocument對象,toJSON()能夠將QJsonDocument轉換回文本形式。
    解析文檔的有效性可使用 !isNull() 進行查詢。
    使用isArray()和isObject()能夠分別查詢一個文檔是否包含了一個數組或一個object。使用array()或object()能夠將包含在文檔中的數組或object提取出來。
    使用fromBinaryData()或fromRawData()也能夠從一個二進制形式建立一個QJsonDocument對象。

二、QJsonDocument成員函數

[static] QJsonDocument QJsonDocument::fromBinaryData(const QByteArray &data, DataValidation validation = Validate)

Validation決定數據是否在使用前檢查數據有效性。

[static] QJsonDocument QJsonDocument::fromJson(const QByteArray &json, QJsonParseError *error = Q_NULLPTR)

json解析爲UTF-8的JSON文檔

[static] QJsonDocument QJsonDocument::fromRawData(const char *data, int size, DataValidation validation = Validate)

使用data數據的前size字節建立一個QJsonDocument對象

[static] QJsonDocument QJsonDocument::fromVariant(const QVariant &variant)

根據variant建立QJsonDocument對象

bool QJsonDocument::isArray() const

bool QJsonDocument::isEmpty() const

bool QJsonDocument::isNull() const

bool QJsonDocument::isObject() const

QJsonObject QJsonDocument::object() const

返回文檔中包含的QJsonObject對象

const char *QJsonDocument::rawData(int *size) const

返回size大小的二進制數據

void QJsonDocument::setArray(const QJsonArray &array)

設置array做爲文檔中的主對象

void QJsonDocument::setObject(const QJsonObject &object)

設置object做爲文檔中的主對象

QByteArray QJsonDocument::toBinaryData() const

返回文檔的二進制格式數據

QByteArray QJsonDocument::toJson(JsonFormat format = Indented) const

QJsonDocument轉換爲UTF-8編碼的format格式的JSON文檔

QVariant QJsonDocument::toVariant() const

返回JSON文檔的QVariant格式

3QJsonDocument對象的構建

A、QJsonDocument fromJson(const QByteArray &json, QJsonParseError *error = Q_NULLPTR)

    fromJson()能夠由QByteArray對象構造一個QJsonDocument對象

QJsonObject json;
json.insert("name", QString("Qt"));
json.insert("version", 5);
json.insert("windows", true);
QJsonDocument document;
document.setObject(json);
QByteArray byte_array = document.toJson(QJsonDocument::Compact);
QJsonParseError json_error;
QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array, &json_error);

B、QJsonDocument fromVariant(const QVariant &variant)

QVariantList people;
QVariantMap bob;
bob.insert("Name", "Bob");
bob.insert("Phonenumber", 123);
QVariantMap alice;
alice.insert("Name", "Alice");
alice.insert("Phonenumber", 321);
people << bob << alice;
QJsonDocument jsonDocument = QJsonDocument::fromVariant(people);
if (!jsonDocument.isNull()) 
{
    qDebug() << jsonDocument.toJson();
}

C、QJsonDocument fromRawData(const char *data, int size, DataValidation validation = Validate)

 

D、QJsonDocument fromBinaryData(const QByteArray &data, DataValidation validation = Validate)

 

3、QJsonArray

1QJsonArray簡介

    QJsonArray封裝了JSON數組。

    JSON數組是值的鏈表,能夠插入和刪除QJsonValue。

    QJsonArrayQVariantList能夠相互轉換。QJsonArray能夠用size(), insert(), removeAt()進行操做,還能夠用標準C++的迭代器模式來迭代其內容。
    QJsonArray是一個隱式共享的類,只要沒有被改變,能夠和建立QJsonArray的document共享數據。
    經過QJsonDocument能夠將一個QJsonArray轉換成或轉換自一個文本形式的JSON

2QJsonArray成員函數

QJsonArray::QJsonArray(std::initializer_list<QJsonValue> args)

構建一個QJsonArray

QJsonArray::QJsonArray(const QJsonArray &other)

void QJsonArray::append(const QJsonValue &value)

QJsonArray尾部插入value

QJsonValue QJsonArray::at(int i) const

返回QJsonArray中索引爲i的QJsonValue

iterator QJsonArray::begin()

const_iterator QJsonArray::begin() const

返回指向數組第一個元素的STL風格迭代器

const_iterator QJsonArray::constBegin() const

返回指向數組第一個元素的const STL風格迭代器

const_iterator QJsonArray::constEnd() const

返回指向數組最後一個元素後的位置的const STL風格迭代器

bool QJsonArray::contains(const QJsonValue &value) const

若是數組中包含value,返回true

int QJsonArray::count() const

返回數組的大小

bool QJsonArray::empty() const

若是數組爲空,返回true

const_iterator QJsonArray::end() const

返回指向數組最後一個元素後的位置的STL風格迭代器

iterator QJsonArray::erase(iterator it)

刪除迭代器it指向的元素,返回指向下一個元素的迭代器

QJsonValue QJsonArray::first() const

返回數組中的第一個值

[static] QJsonArray QJsonArray::fromStringList(const QStringList &list)

將一個字符串鏈表list轉換爲QJsonArray

[static] QJsonArray QJsonArray::fromVariantList(const QVariantList &list)

將鏈表list轉換爲QJsonArray

4、QJsonObject

1QJsonObject簡介

QJsonObject類用於封裝JSON對象。JSON對象是包含鍵值對的鏈表,其中鍵是惟一的字符串,其值由QJsonValue表明。

QJsonObject能夠QVariantMap相互轉換,能夠用size()來得到鍵值對的數目,insert()remove()分別用來插入和刪除pair。能夠用標準C++的迭代器模式(iterator pattern)來迭代其內容。
    QJsonObject是一個隱式共享的類,只要沒有被改變過,QJsonObject會和建立它的document共享數據。
    能夠經過QJsonDocument將QJsonObject和文本格式相互轉換。

二、QJsonObject成員函數

QJsonObject::QJsonObject(std::initializer_list<QPair<QString, QJsonValue> > args)

使用鍵值對鏈表構建QJsonObject對象

QJsonObject::QJsonObject(const QJsonObject &other)

 

iterator QJsonObject::begin()

const_iterator QJsonObject::begin() const

返回指向JSON對象的第一個元素的STL風格的迭代器

const_iterator QJsonObject::constBegin() const

返回指向JSON對象的第一個元素的const STL風格的迭代器

const_iterator QJsonObject::constEnd() const

返回SJON對象的最後一個元素後的位置的const STL風格的迭代器

const_iterator QJsonObject::constFind(const QString &key) const

返回一個指向鍵值對中鍵爲key的元素的const迭代器

bool QJsonObject::contains(const QString &key) const

若是JSON對象中包含鍵key,返回true

int QJsonObject::size() const

int QJsonObject::count() const

返回JSON對象中鍵值對的數量

bool QJsonObject::empty() const

bool QJsonObject::isEmpty() const

若是JSON對象爲空,返回true

iterator QJsonObject::find(const QString &key)

const_iterator QJsonObject::find(const QString &key) const

返回指向JSON對象中鍵爲key的鍵值對的迭代器

[static] QJsonObject QJsonObject::fromVariantHash(const QVariantHash &hash)

hash轉換爲JSON對象

[static] QJsonObject QJsonObject::fromVariantMap(const QVariantMap &map)

map轉換爲JSON對象

iterator QJsonObject::insert(const QString &key, const QJsonValue &value)

插入鍵爲key,值爲value的鍵值對,返回插入鍵值對的迭代器

QStringList QJsonObject::keys() const

返回JSON對象的全部鍵的鏈表

void QJsonObject::remove(const QString &key)

刪除JSON對象中的key

QJsonValue QJsonObject::take(const QString &key)

刪除JSON對象中的鍵key,返回key對應的QJsonValue

QVariantHash QJsonObject::toVariantHash() const

JSON對象轉換爲QVariantHash

QVariantMap QJsonObject::toVariantMap() const

JSON對象轉換爲QVariantMap

QJsonValue QJsonObject::value(const QString &key) const

返回key對應的QJsonValue

5、QJsonParseError

1QJsonParseError簡介

    QJsonParseError類用於在JSON解析中報告錯誤。

常量

 

描述

 QJsonParseError::NoError

 0

未發生錯誤

 QJsonParseError::UnterminatedObject

 1

對象不正確地終止以右花括號結束

 QJsonParseError::MissingNameSeparator

 2

分隔不一樣項的逗號丟失

 QJsonParseError::UnterminatedArray

 3

數組不正確地終止以右中括號結束

 QJsonParseError::MissingValueSeparator

 4

對象中分割 key/value 的冒號丟失

 QJsonParseError::IllegalValue

 5

值是非法的

 QJsonParseError::TerminationByNumber

 6

在解析數字時,輸入流結束

 QJsonParseError::IllegalNumber

 7

數字格式不正確

 QJsonParseError::IllegalEscapeSequence

 8

在輸入時,發生一個非法轉義序列

 QJsonParseError::IllegalUTF8String

 9

在輸入時,發生一個非法 UTF8 序列

 QJsonParseError::UnterminatedString

 10

字符串不是以引號結束

 QJsonParseError::MissingObject

 11

一個對象是預期的,可是不能被發現

 QJsonParseError::DeepNesting

 12

對解析器來講,JSON 文檔嵌套太深

 QJsonParseError::DocumentTooLarge

 13

對解析器來講,JSON 文檔太大

 QJsonParseError::GarbageAtEnd

 14

解析的文檔在末尾處包含額外的亂碼

二、QJsonParseError成員函數

QString QJsonParseError::errorString() const

返回JSON解析錯誤時報告的錯誤信息

5、QJsonValue

1QJsonValue簡介

    QJsonValue類封裝了JSON中的值。JSON中的值有6種基本類型:

    bool           QJsonValue::Bool

    double         QJsonValue::Double

    string         QJsonValue::String

    array          QJsonValue::Array

    object         QJsonValue::Object

    null           QJsonValue::Null

    Undefined      QJsonValue::Undefined

    value能夠是以上任何一種數據類型。另外,QJsonValue有一個特殊的flag來表示未定義類型。能夠用isUndefined()來查詢 
    能夠用type()或isBool(),isString()等來查詢value的類型。相似的,能夠用toBool()toString()等將一個value轉換成存儲在該value內部的類型。

2QJsonValue成員函數

[static] QJsonValue QJsonValue::fromVariant(const QVariant &variant)

variant轉換爲QJsonValue

bool QJsonValue::isArray() const

若是QJsonValue包含一個數組,返回true

bool QJsonValue::isBool() const

若是QJsonValue包含一個bool,返回true

bool QJsonValue::isDouble() const

若是QJsonValue包含一個double,返回true

bool QJsonValue::isNull() const

若是QJsonValue包含一個Null,返回true

bool QJsonValue::isObject() const

若是QJsonValue包含一個object,返回true

bool QJsonValue::isString() const

若是QJsonValue包含一個string,返回true

bool QJsonValue::isUndefined() const

若是QJsonValue包含一個undefined,返回true

QJsonArray QJsonValue::toArray(const QJsonArray &defaultValue) const

QJsonValue轉換爲QJsonArray並返回,若是類型不是array,返回默認值defaultValue

QJsonArray QJsonValue::toArray() const

QJsonValue轉換爲QJsonArray並返回

bool QJsonValue::toBool(bool defaultValue = false) const

QJsonValue轉換爲bool並返回

double QJsonValue::toDouble(double defaultValue = 0) const

QJsonValue轉換爲double並返回

int QJsonValue::toInt(int defaultValue = 0) const

QJsonValue轉換爲int並返回

QJsonObject QJsonValue::toObject(const QJsonObject &defaultValue) const

QJsonObject QJsonValue::toObject() const

QJsonValue轉換爲QJsonObject並返回

QString QJsonValue::toString(const QString &defaultValue = QString()) const

QJsonValue轉換爲QString並返回

Type QJsonValue::type() const

返回QJsonValue的類型

6、JSON解析編程

1JSON解析流程

    JSON解析的流程以下:

    A、將對應的字符串生成QJsonDocument對象

    B、判斷QJsonDocument對象是QJsonObject仍是QJsonArray

    C、若是是QJsonObject類型,獲取一個QJsonObject對象,而後根據QJsonObjectAPI函數進行解析

    D、若是是QJsonArray類型,獲取一個QJsonArray對象,而後根據QJsonArrayAPI函數進行解析

    E、根據獲取的QJsonObjectQJsonArray取得QJsonValue類型的數據

    F、迭代分解數據獲取各個值

    JSON解析流程實例:

#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>
#include <QString>
#include <QStringList>
#include <QDebug>
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    QString json("{\"name\":\"scorpio\", \"year\":2016, \"array\":[30, \"hello\", true]}");
    QJsonParseError jsonerror;
    QJsonDocument doc = QJsonDocument::fromJson(json.toLatin1(), &jsonerror);
    if (!doc.isNull() && jsonerror.error == QJsonParseError::NoError)
    {
        if(doc.isObject())
        {
            QJsonObject object = doc.object();
            QStringList list = object.keys();
            for(int i = 0; i < list.count(); i++)
            {
                qDebug() << list.at(i);
            }
            QJsonObject::iterator it = object.begin();
            while(it != object.end())
            {
                switch(it.value().type())
                {
                case QJsonValue::String:
                {
                    qDebug() << "Type is string";
                    QJsonArray sub = it.value().toArray();
                    qDebug() << it.key() << "=" << it.value().toString();
                    break;
                }
                case QJsonValue::Array:
                {
                    qDebug() << "Type is Array";
                    qDebug() << it.key() << "=" << it.value().toArray();
                    QJsonArray sub = it.value().toArray();
                    qDebug() << "index 1:" << sub.at(0).toDouble();
                    qDebug() << "index 2:" << sub.at(1).toString();
                    qDebug() << "index 3:" << sub.at(2).toBool();
                    break;
                }
                case QJsonValue::Bool:
                {
                    qDebug() << "Type is Bool";
                    qDebug() << it.key() << "=" << it.value().toBool();
                    break;
                }
                case QJsonValue::Double:
                {
                    qDebug() << "Type is Double";
                    qDebug() << it.key() << "=" << it.value().toDouble();
                    break;
                }
                case QJsonValue::Object:
                {
                    qDebug() << "Type is Object";
                    qDebug() << it.key() << "=" << it.value().toObject();
                    break;
                }
                case QJsonValue::Null:
                {
                    qDebug() << "Type is Null";
                    qDebug() << it.key() << "= NULL" ;
                    break;
                }
                case QJsonValue::Undefined:
                {
                    qDebug() << "Type is Undefined";
                    break;
                }
                }
                it++;
            }
        }
    }
 
    return a.exec();
}

2QJsonObject

JSON對象:

{

    "Cross Platform": true,

    "From": 2016,

    "Name": "Qt"

}

A、構建JSON對象

    // 構建 JSON 對象

    QJsonObject json;

    json.insert("Name", "Qt");

    json.insert("From", 2016);

    json.insert("Cross Platform", true);

B、構建JSON文檔

    // 構建 JSON 文檔

    QJsonDocument document;

    document.setObject(json);

    QByteArray byteArray = document.toJson();

    QString strJson(byteArray);

C、解析JSON

   

 QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(byteArray, &jsonError);  
    if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
    { 
        if (doucment.isObject())
        { 
            QJsonObject object = doucment.object();  
            if (object.contains("Name"))
            {  // 包含指定的 key
                QJsonValue value = object.value("Name"); 
                if (value.isString())
                {  // 判斷 value 是否爲字符串
                    QString strName = value.toString(); 
                    qDebug() << "Name : " << strName;
                }
            }
            if (object.contains("From"))
            {
                QJsonValue value = object.value("From");
                if (value.isDouble())
                {
                    int nFrom = value.toVariant().toInt();
                    qDebug() << "From : " << nFrom;
                }
            }
            if (object.contains("Cross Platform"))
            {
                QJsonValue value = object.value("Cross Platform");
                if (value.isBool())
                {
                    bool bCrossPlatform = value.toBool();
                    qDebug() << "CrossPlatform : " << bCrossPlatform;
                }
            }
        }
    }

3QJsonArray

JSON數組:

[

    "Qt",

    5.7,

    true

]

A、構建JSON數組

    // 構建 JSON 數組

    QJsonArray json;

    json.append("Qt");

    json.append(5.7);

    json.append(true);

B、構建JSON文檔

    // 構建 JSON 文檔

    QJsonDocument document;

    document.setArray(json);

    QByteArray byteArray = document.toJson(QJsonDocument::Compact);

    QString strJson(byteArray);

C、解析JSON

   

 QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(byteArray, &jsonError); 
    if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)) 
    { 
        if (doucment.isArray()) 
        { 
            QJsonArray array = doucment.array();  
            int nSize = array.size();  
            for (int i = 0; i < nSize; ++i) 
            {  // 遍歷數組
                QJsonValue value = array.at(i);
                if (value.type() == QJsonValue::String) 
                {
                    QString strName = value.toString();
                    qDebug() << strName;
                }
                if (value.type() == QJsonValue::Double) 
                {
                    double dVersion = value.toDouble();
                    qDebug() << dVersion;
                }
                if (value.type() == QJsonValue::Bool) 
                {
                    bool bCrossPlatform  = value.toBool();
                    qDebug() << bCrossPlatform;
                }
            }
        }
    }

4、複雜JSON

{

    "Company": "Digia",

    "From": 1991,

    "Name": "Qt",

    "Page": {

        "Developers": "https://www.qt.io/developers/",

        "Download": "https://www.qt.io/download/",

        "Home": "https://www.qt.io/"},

    "Version": [

        4.8,

        5.2,

        5.7]

}

 

   // 構建 Json 數組 - Version
    QJsonArray versionArray;
    versionArray.append(4.8);
    versionArray.append(5.2);
    versionArray.append(5.7);
 
    // 構建 Json 對象 - Page
    QJsonObject pageObject;
    pageObject.insert("Home", "https://www.qt.io/");
    pageObject.insert("Download", "https://www.qt.io/download/");
    pageObject.insert("Developers", "https://www.qt.io/developers/");
 
    // 構建 Json 對象
    QJsonObject json;
    json.insert("Name", "Qt");
    json.insert("Company", "Digia");
    json.insert("From", 1991);
    json.insert("Version", QJsonValue(versionArray));
    json.insert("Page", QJsonValue(pageObject));
 
    // 構建 Json 文檔
    QJsonDocument document;
    document.setObject(json);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString strJson(byteArray);
        //解析JSON
    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(byteArray, &jsonError);
    if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
    {
        if (doucment.isObject())
        {
            QJsonObject object = doucment.object();
            if (object.contains("Name"))
            {
                QJsonValue value = object.value("Name");
                if (value.isString())
                {
                    QString strName = value.toString();
                    qDebug() << "Name : " << strName;
                }
            }
            if (object.contains("Company"))
            {
                QJsonValue value = object.value("Company");
                if (value.isString())
                {
                    QString strCompany = value.toString();
                    qDebug() << "Company : " << strCompany;
                }
            }
            if (object.contains("From"))
            {
                QJsonValue value = object.value("From");
                if (value.isDouble())
                {
                    int nFrom = value.toVariant().toInt();
                    qDebug() << "From : " << nFrom;
                }
            }
            if (object.contains("Version"))
            {
                QJsonValue value = object.value("Version");
                if (value.isArray())
                {
                    QJsonArray array = value.toArray();
                    int nSize = array.size();
                    for (int i = 0; i < nSize; ++i)
                    {
                        QJsonValue value = array.at(i);
                        if (value.isDouble())
                        {
                            double dVersion = value.toDouble();
                            qDebug() << "Version : " << dVersion;
                        }
                    }
                }
            }
            if (object.contains("Page"))
            {
                QJsonValue value = object.value("Page");
                if (value.isObject())
                {
                    QJsonObject obj = value.toObject();
                    if (obj.contains("Home"))
                    {
                        QJsonValue value = obj.value("Home");
                        if (value.isString())
                        {
                            QString strHome = value.toString();
                            qDebug() << "Home : " << strHome;
                        }
                    }
                    if (obj.contains("Download"))
                    {
                        QJsonValue value = obj.value("Download");
                        if (value.isString())
                        {
                            QString strDownload = value.toString();
                            qDebug() << "Download : " << strDownload;
                        }
                    }
                    if (obj.contains("Developers"))
                    {
                        QJsonValue value = obj.value("Developers");
                        if (value.isString())
                        {
                            QString strDevelopers = value.toString();
                            qDebug() << "Developers : " << strDevelopers;
                        }
                    }
                }
            }
        }
    }
相關文章
相關標籤/搜索