How to use JSON data with QT C++

How to use JSON data with QT C++

Hello everyone, in this article we are going to talk about manipulating and handling the one of most popular data transferring method JSON data with QT Framework in C++.

Let's get started.

First of All What is JSON ?

JSON is a data store and transfer object between different type of platforms and systems. JSON stands for JavaScript Object Notation.

You can see a sample JSON Data below:


{
    "name": "Burak Hamdi",
    "surname": "TUFAN",
    "age": 26,
    "address": {
        "city": "Istanbul",
        "country": "TURKEY"
    },
    "phone": [
        "0555555555",
        "01111111111"
    ]
}

Let's manipulate some datas with JSON format with QT C++.

Firstly you need to add below libraries in your related header file.


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

First let's encode some personal data into JSON format.


    //create main object for whole json data
    QJsonObject mainObject;

    //insert single datas first
    mainObject.insert("name", "Burak Hamdi");
    mainObject.insert("surname", "TUFAN");
    mainObject.insert("age",26);

    //create an object for inner object of main object
    QJsonObject address;
    address.insert("city", "Istanbul");
    address.insert("country", "TURKEY");
    //insert the inner json object inside main object
    mainObject.insert("address",address);

    //create a json array for main jsonobject
    QJsonArray phones;
    phones.push_back("0555555555");
    phones.push_back("01111111111");

    // we added JSON array into our main json object
    mainObject.insert("phone", phones);

    // lastly we created a JSON document and set mainObject as object of document
    QJsonDocument jsonDoc;
    jsonDoc.setObject(mainObject);

    // Write our jsondocument as json with JSON format
    ui->txtJsonEncoded->setPlainText( jsonDoc.toJson() );

Now What did we do above :

  • First we created a JSON object to load all datas on it. And we added our single datas like name surname directly.
  • Later we want to add a JSON object into above object. So we created another QJSONObject load its datas.
  • After we added datas into second object, we inserted second JSON object into first JSON onject.
  • Then we wanted to add an array into our main object. We created a QJsonArray and we pushed back our datas into this array. Then insert this Json Array into main object.
  • At last we create a QJsonDocument and we set our main object as object ofQJsonDocument.
  • So all of our datas now in our Json Document and we are ready to transfer it.
  • To write our data as a string with JSON format we use toJson() method from QJsonDocument.
Until here we have seen to encode a dataset into JSON format.

Important note
You cannot enable json key sorting, Qt sorts the keys alphabetically and there is no way to change it. (With Qt 5.11)


Now let's decode a JSONEncoded data.

Blow code block you will see the decoding a JSON data with QT C++.


    //Convert the QString text to Bytearray first
    QByteArray jsonData = ui->txtJsonEncoded->toPlainText().toUtf8();
    if(jsonData.isEmpty() == true) qDebug() << "Need to fill JSON data";

    //Assign the json text to a JSON object
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonData);
    if(jsonDocument.isObject() == false) qDebug() << "It is not a JSON object";

    //Then get the main JSON object and get the datas in it
    QJsonObject object = jsonDocument.object();

    //Access the sibgle values
    QJsonValue name = object.value("name");
    QJsonValue surname = object.value("surname");
    QJsonValue age = object.value("age"); //this value is integer

    //Access the inner JSON object and its inside data. objects will be within { } curly braces
    QJsonObject address = object.value("address").toObject();
    QJsonValue addr_city = address.value("city");
    QJsonValue addr_country = address.value("country");

    //access the array within the JSON object. arrays will be within [ ] squared braces
    QJsonArray phones = object.value("phone").toArray();
    qDebug() << "There are " + QString::number(phones.size()) + " items in phones array";
    QString phoneList = "";
    for(unsigned int i=0; i<phones.size(); i++ ) phoneList.append(phones.at(i).toString() + "\n");

    QString decodedData = "";

    decodedData.append("Name : " + name.toString() + "\n");
    decodedData.append("Surname : " + surname.toString() + "\n");
    decodedData.append("Age : " + QString::number(age.toInt()) + "\n");

    decodedData.append("Address : \n");
    decodedData.append("-City : " + addr_city.toString() + "\n");
    decodedData.append("-Country : " + addr_country.toString() + "\n");

    decodedData.append("Phones : \n" + phoneList + "\n");

    ui->txtJsonDecoded->setPlainText(decodedData);

    if(name.isString() == true) qDebug() << "name is a string";
    qDebug() << "Firstname : " + name.toString();

Here we make reverse action of encoding.

  • First we converted incoming data into ByteArray and check it for data is exist.
  • After controlling data is exist then we assigned to a JsonDocument and control for correct JSON Data.
  • And then we create data type which exist in our JSON data. We created QJsonValue, QJsonObject and QJsonArray.
  • Then we get the related datas and assigned them to created variables.
  • For QJsonObjects we got datas into variabbles again
  • For QJsonArrays we get datas and read all datas as normal arrays.
  • Lastly collect all datas within a QString and print in a Textbox.
Now we are ready to manipulate datas with Json format.
That is all in this article.
Burak Hamdi TUFAN

Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...