Hello Qt -- QT5 parsing Json file

1, Introduction to Qt5 Jason

QT4 uses the third-party library QJson to parse JSON files.

QT5 adds a new class to handle JSON. All classes begin with QJson and are included in the QtCore module. Six related categories are added to QT5:

QJsonArray

Encapsulating JSON arrays

QJsonDocument

Reading and writing JSON documents

QJsonObject

Encapsulating JSON objects

QJsonObject::iterator

STL style non const traverser for traversing QJsonObject

QJsonParseError

Report errors during JSON processing

QJsonValue

Encapsulate JSON values

2, QJsonDocument

1. Introduction to QJsonDocument

QJsonDocument provides a way to read and write Json documents.

QJsonDocument is a class that contains complete JSON documents. It supports reading and writing JSON documents in UTF-8 encoded text and QT's own binary format.

JSON documents can use QJsonDocument::fromJson() to convert the text form based on JSON documents to QJsonDocument objects, and toJSON() can convert QJsonDocument back to text form.
The validity of parsing documents can be used! isNull() to query.
Use isArray() and isObject() to query whether a document contains an array or an object. Use array() or object() to extract the array or object contained in the document.
Using fromBinaryData() or fromRawData(), you can also create a QJsonDocument object from a binary form.

2. QJsonDocument member function

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

Validation determines whether the data is checked for validity before use.

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

Parsing JSON into a JSON document of UTF-8

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

Create a QJsonDocument object using the first size byte of data

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

Create QJsonDocument object based on variant

bool QJsonDocument::isArray() const

bool QJsonDocument::isEmpty() const

bool QJsonDocument::isNull() const

bool QJsonDocument::isObject() const

QJsonObject QJsonDocument::object() const

Returns the QJsonObject object contained in the document

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

Return binary data of size

void QJsonDocument::setArray(const QJsonArray &array)

Set array as the main object in the document

void QJsonDocument::setObject(const QJsonObject &object)

Set object as the main object in the document

QByteArray QJsonDocument::toBinaryData() const

Returns the binary format data of the document

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

Convert QJsonDocument into a JSON document in UTF-8 encoded format

QVariant QJsonDocument::toVariant() const

Returns the of the JSON document Q Variant format

3. Construction of QJsonDocument object

A,fromJson

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

A jsonqfromdocument () object can be constructed by jsonqmarray()

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,fromVariant

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,fromRawData

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

D, fromBinaryData

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

3, QJsonArray

1. Introduction to QJsonArray

QJsonArray encapsulates JSON arrays.

JSON array is a linked list of values. QJsonValue can be inserted and deleted.

QJsonArray and QVariantList can be converted to each other. QJsonArray can be operated with size(), insert(), removeAt(), and its contents can be iterated with the iterator mode of standard C + +.
QJsonArray is an implicitly shared class. As long as it has not been changed, it can share data with the document that created QJsonArray.
A QJsonArray can be converted into or from a JSON in text form through QJsonDocument.

2. QJsonArray member function

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

Build a QJsonArray

QJsonArray::QJsonArray(const QJsonArray &other)

void QJsonArray::append(const QJsonValue &value)

Insert value at the end of QJsonArray

QJsonValue QJsonArray::at(int i) const

Returns the data with index i in QJsonArray Q JsonValue value

iterator QJsonArray::begin()

const_iterator QJsonArray::begin() const

Returns an STL style iterator that points to the first element of the array

const_iterator QJsonArray::constBegin() const

Returns a const STL style iterator pointing to the first element of the array

const_iterator QJsonArray::constEnd() const

Returns a const STL style iterator that points to the position after the last element of the array

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

Returns true if the array contains value

int QJsonArray::count() const

Returns the size of the array

bool QJsonArray::empty() const

Returns true if the array is empty

const_iterator QJsonArray::end() const

Returns an STL style iterator that points to the position after the last element of the array

iterator QJsonArray::erase(iterator it)

Delete the element pointed to by the iterator it and return the iterator pointing to the next element

QJsonValue QJsonArray::first() const

Returns the first value in the array

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

Convert a string linked list to QJsonArray

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

Convert linked list to QJsonArray

4, QJsonObject

1. Introduction to QJsonObject

The QJsonObject class is used to encapsulate JSON objects. JSON object is a linked list containing key value pairs, where the key is a unique string, and its value is represented by QJsonValue.

QJsonObject and QVariantMap can be converted to each other. You can use size() to obtain the number of key value pairs. insert() and remove() are used to insert and delete pairs respectively. Its contents can be iterated with the iterator pattern of standard C + +.
QJsonObject is an implicitly shared class. As long as it has not been changed, QJsonObject will share data with the document that created it.
QJsonObject and text format can be converted to each other through QJsonDocument.

2. QJsonObject member function

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

Build QJsonObject object using key value pair linked list

iterator QJsonObject::begin()
const_iterator QJsonObject::begin() const

Returns an STL style iterator that points to the first element of a JSON object

const_iterator QJsonObject::constBegin() const

Returns a const STL style iterator that points to the first element of a JSON object

const_iterator QJsonObject::constEnd() const

const STL style iterator that returns the position after the last element of the SJON object

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

Returns a const iterator that points to the element with key in the key value pair

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

Returns true if the JSON object contains the key

int QJsonObject::size() const

int QJsonObject::count() const

Returns the number of key value pairs in a JSON object

bool QJsonObject::empty() const

bool QJsonObject::isEmpty() const

Returns true if the JSON object is empty

iterator QJsonObject::find(const QString &key)

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

Returns an iterator pointing to a key value pair with a key in a JSON object

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

Convert hash to JSON object

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

Convert map to JSON object

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

Insert a key value pair with key and value, and return the iterator of the inserted key value pair

QStringList QJsonObject::keys() const

Returns a linked list of all keys of a JSON object

void QJsonObject::remove(const QString &key)

Delete key in JSON object

QJsonValue QJsonObject::take(const QString &key)

Delete the key in the JSON object and return the QJsonValue corresponding to the key

QVariantHash QJsonObject::toVariantHash() const

Convert JSON objects to QVariantHash

QVariantMap QJsonObject::toVariantMap() const

Convert JSON objects to QVariantMap

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

Return the corresponding key Q JsonValue value

5, QJsonParseError

1. Introduction to QJsonParseError

The QJsonParseError class is used to report errors in JSON parsing.

constant

Value

describe

 QJsonParseError::NoError

 0

No error occurred

 QJsonParseError::UnterminatedObject

 1

The object terminated incorrectly, ending with a closing curly bracket

 QJsonParseError::MissingNameSeparator

 2

Missing comma separating different items

 QJsonParseError::UnterminatedArray

 3

The array terminated incorrectly, ending with a closing bracket

 QJsonParseError::MissingValueSeparator

 4

Missing colon to split key/value in object

 QJsonParseError::IllegalValue

 5

The value is illegal

 QJsonParseError::TerminationByNumber

 6

When parsing a number, the input stream ends

 QJsonParseError::IllegalNumber

 7

The number format is incorrect

 QJsonParseError::IllegalEscapeSequence

 8

An illegal escape sequence occurred during input

 QJsonParseError::IllegalUTF8String

 9

An illegal UTF8 sequence occurred during input

 QJsonParseError::UnterminatedString

 10

The string does not end in quotation marks

 QJsonParseError::MissingObject

 11

An object is expected, but cannot be found

 QJsonParseError::DeepNesting

 12

JSON documents are nested too deeply for parsers

 QJsonParseError::DocumentTooLarge

 13

JSON documents are too large for parsers

 QJsonParseError::GarbageAtEnd

 14

The parsed document contains additional garbled code at the end

2. QJsonParseError member function

QString QJsonParseError::errorString() const

Returns the error information reported when the JSON parsing error occurs

6, QJsonValue

1. Introduction to QJsonValue

The QJsonValue class encapsulates the values in JSON. There are six basic types of values in JSON:

bool   QJsonValue::Bool

double QJsonValue::Double

string QJsonValue::String

array   QJsonValue::Array

object QJsonValue::Object

null   QJsonValue::Null

Undefined QJsonValue::Undefined

value can be any type of data. In addition, QJsonValue has a special flag to represent undefined types. You can use isUndefined() to query.  
You can use type(), isBool(), isString(), etc. to query the type of value. Similarly, you can use toBool(), toString(), etc. to convert a value into a type stored inside the value.

2. QJsonValue member function

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

Convert variant to QJsonValue

bool QJsonValue::isArray() const

Returns true if QJsonValue contains an array

bool QJsonValue::isBool() const

Returns true if QJsonValue contains a bool

bool QJsonValue::isDouble() const

If QJsonValue contains a double, return true

bool QJsonValue::isNull() const

Returns true if QJsonValue contains a Null

bool QJsonValue::isObject() const

If QJsonValue contains an object, return true

bool QJsonValue::isString() const

Returns true if QJsonValue contains a string

bool QJsonValue::isUndefined() const

If QJsonValue contains an undefined, return true

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

Convert QJsonValue to QJsonArray and return it. If the type is not array, return the default value defaultValue

QJsonArray QJsonValue::toArray() const

Convert QJsonValue to QJsonArray and return

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

Convert QJsonValue to bool and return

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

Convert QJsonValue to double and return

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

Convert QJsonValue to int and return

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

QJsonObject QJsonValue::toObject() const

Convert QJsonValue to QJsonObject and return

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

Convert QJsonValue to QString and return

Type QJsonValue::type() const

Returns the type of QJsonValue

7, JSON parsing programming

1. JSON parsing process

The JSON parsing process is as follows:

A. Generate the corresponding string into a QJsonDocument object

B. Judge whether the QJsonDocument object is a QJsonObject or a QJsonArray

C. If it is a QJsonObject type, get a QJsonObject object and parse it according to the API function of QJsonObject

D. If it is a QJsonArray type, get a QJsonArray object and parse it according to the API function of QJsonArray

E. Obtain QJsonValue type data according to the obtained QJsonObject or QJsonArray

F. Iteratively decompose the data to obtain each value

JSON parsing process instance:

#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();
}

2,QJsonObject

JSON object:

{
    "Cross Platform": true,
    "From": 2016,
    "Name": "Qt"
}

A. Building JSON objects

    // Building JSON objects
    QJsonObject json;
    json.insert("Name", "Qt");
    json.insert("From", 2016);
    json.insert("Cross Platform", true);

B. Building JSON documents

    // Building JSON documents
    QJsonDocument document;
    document.setObject(json);
    QByteArray byteArray = document.toJson();
    QString strJson(byteArray);

C. Parsing 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"))
            {  //Contains the specified key
                QJsonValue value = object.value("Name"); 
                if (value.isString())
                {  //Judge whether , value , is a string
                    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;
                }
            }
        }
    }

3,QJsonArray

JSON array:

[
    "Qt",
    5.7,
    true
]

A. Building JSON arrays

    // Building JSON arrays
    QJsonArray json;
    json.append("Qt");
    json.append(5.7);
    json.append(true);

B. Building JSON documents

    // Building JSON documents
    QJsonDocument document;
    document.setArray(json);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString strJson(byteArray);

C. Parsing 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) 
            {  //Traversal array
                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. Complex 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]
}
    //Build Json array - Version
    QJsonArray versionArray;
    versionArray.append(4.8);
    versionArray.append(5.2);
    versionArray.append(5.7);

    //Build # Json # object - 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/");

    //Building # Json # objects
    QJsonObject json;
    json.insert("Name", "Qt");
    json.insert("Company", "Digia");
    json.insert("From", 1991);
    json.insert("Version", QJsonValue(versionArray));
    json.insert("Page", QJsonValue(pageObject));

    //Build # Json # documents
    QJsonDocument document;
    document.setObject(json);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString strJson(byteArray);

    //Parsing 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;
                        }
                    }
                }
            }
        }
    }

Keywords: Qt

Added by TimUSA on Sat, 05 Mar 2022 18:27:34 +0200