Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Qt JSON Construction and Parsing Tutorial

Tech May 14 1

This tutoiral demonstrates how to build and parse JSON data using Qt's JSON classes, based on a practical example structure.

Sample JSON Data

{
    "name": "BeJson",
    "url": "http://www.bejson.com",
    "page": 88,
    "isNonProfit": true,
    "address": {
        "city": "江苏苏州",
        "country": "中国",
        "street": "科技园路"
    },
    "links": [
        {
            "name": "Google",
            "url": "http://www.google.com"
        },
        {
            "name": "Baidu",
            "url": "http://www.baidu.com"
        },
        {
            "name": "SoSo",
            "url": "http://www.SoSo.com"
        }
    ]
}

Implementation

#include <QtCore/QCoreApplication>
#include <QDir>
#include <QFile>
#include <QDebug>

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>

void serializeJson()
{
    QJsonObject dataObject;

    // Add basic string and numeric fields
    dataObject.insert("name", "BeJson");
    dataObject.insert("url", "http://www.bejson.com");
    dataObject.insert("page", 88);
    dataObject.insert("isNonProfit", true);

    // Add nested address object
    QJsonObject locationObject;
    locationObject.insert("street", "科技园路");
    locationObject.insert("city", "江苏苏州");
    locationObject.insert("country", "中国");

    dataObject.insert("address", locationObject);

    // Add array of link objects
    QJsonObject googleItem;
    googleItem.insert("name", "Google");
    googleItem.insert("url", "http://www.google.com");

    QJsonObject baiduItem;
    baiduItem.insert("name", "Baidu");
    baiduItem.insert("url", "http://www.baidu.com");

    QJsonObject sosoItem;
    sosoItem.insert("name", "SoSo");
    sosoItem.insert("url", "http://www.SoSo.com");

    QJsonArray contactsArray;
    contactsArray.append(googleItem);
    contactsArray.append(baiduItem);
    contactsArray.append(sosoItem);

    dataObject.insert("links", contactsArray);

    // Convert to JSON string
    QJsonDocument doc(dataObject);
    QByteArray jsonData = doc.toJson(QJsonDocument::Compact);

    qDebug().noquote() << QString::fromUtf8(jsonData);

    // Write to file
    QString appDir = QCoreApplication::applicationDirPath();
    QString filePath = QDir::cleanPath(appDir + QDir::separator() + "output.json");
    QFile file(filePath);
    
    if (file.open(QIODevice::WriteOnly)) {
        file.write(jsonData);
        file.close();
        qDebug() << "File written successfully:" << filePath;
    } else {
        qDebug() << "Failed to open file for writing";
    }
}

void deserializeJson()
{
    // Read JSON from file
    QString appDir = QCoreApplication::applicationDirPath();
    QString filePath = QDir::cleanPath(appDir + QDir::separator() + "output.json");
    QFile file(filePath);
    
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file for reading";
        return;
    }
    
    QByteArray jsonData = file.readAll();
    file.close();

    // Parse JSON string
    QJsonDocument doc = QJsonDocument::fromJson(jsonData);
    
    if (doc.isNull() || !doc.isObject()) {
        qDebug() << "Invalid JSON format";
        return;
    }

    QJsonObject dataObject = doc.object();
    
    // Iterate through all keys
    for (auto it = dataObject.begin(); it != dataObject.end(); ++it) {
        QString key = it.key();
        QJsonValue val = it.value();

        if (val.isBool()) {
            qDebug() << key << ":" << val.toBool();
        } 
        else if (val.isString()) {
            qDebug() << key << ":" << val.toString();
        } 
        else if (val.isDouble()) {
            qDebug() << key << ":" << val.toDouble();
        } 
        else if (val.isObject()) {
            qDebug() << key << ":";
            
            QJsonObject locationObject = val.toObject();
            qDebug() << "    street:" << locationObject["street"].toString();
            qDebug() << "    city:" << locationObject["city"].toString();
            qDebug() << "    country:" << locationObject["country"].toString();
        } 
        else if (val.isArray()) {
            qDebug() << key << ":";
            
            QJsonArray linksArray = val.toArray();
            for (int i = 0; i < linksArray.size(); ++i) {
                QJsonObject itemObject = linksArray[i].toObject();
                QString name = itemObject["name"].toString();
                QString url = itemObject["url"].toString();
                
                qDebug() << "    name:" << name << ", url:" << url;
            }
        }
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    
    serializeJson();
    qDebug() << "---";
    deserializeJson();
    
    return 0;
}

Key Classes Used

  • QJsonObject: Represents a JSON object (key-value pairs)
  • QJsonArray: Represents a JSON array (ordered list of values)
  • QJsonDocument: Container for JSON data, used for conversion between JSON and byte array
  • QJsonValue: Represents a single JSON value with type detection methods

Type Detection Methods

QJsonValue provides various methods to check the type of a value:

  • isBool() - Check if value is boolean
  • isString() - Check if value is string
  • isDouble() - Check if value is number
  • isObject() - Check if value is nested object
  • isArray() - Check if value is array

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.