Evgenii Legotckoi
Jan. 2, 2016, 9:33 p.m.

Qt/C++ - Lesson 041. JSON file – How to get from site and parsing it

In the process of writing programs EColor appeared a problem in which it was necessary in some way to notify the user that a new version of the program. The solution to this problem was the presence of JSON file on the site. With QNetworkAccessManager get a JSON file and produce his analysis, thanks to the class library Qt: QJsonDocument , QJsonObject , QJsonArray . In the case of the program on the website EColor contains JSON file with the name of the program, the full version in string form and three entities to the major part of the version, minor and patch version. When parsing the file is compared with the current version of the program that is on the website. If the site is lined with a newer version, the program will notify the user.


For example, at http://www.evileg.ru/it_example.json JSON file is located on a site with the following content:

  1. {
  2. "departament": "it",
  3. "employees": [
  4. {"firstName": "John", "lastName": "Doe"},
  5. {"fisrtName": "Michael", "lastName": "Smith"},
  6. {"firstName": "Anna", "lastName": "Jones"}
  7. ],
  8. "number" : 3
  9. }

At the root of the object file is located three objects, the second of which is an array. The first object - a string property " departament ", which contains the name of the department. The second object - an array containing the names of employees. A third object - is the employees number of type Integer .

Project structure for JSON parsing

  • JSONParser.pro - the profile of the project;
  • main.cpp - the main project source code file;
  • widget.h - header file of the application window, which contains a QTextEdit field, which will be placed in the result of parsing the file;
  • widget.cpp - source file with QNetworkAccessManager.
  • widget.ui - file interface.

JSONParser.pro

Do not forget to connect the network module to the profile of the project, to be able to work with the class QNetworkAccessManager .

  1. #-------------------------------------------------
  2. #
  3. # Project created by QtCreator 2016-01-02T13:12:55
  4. #
  5. #-------------------------------------------------
  6.  
  7. QT += core gui network
  8.  
  9. greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
  10.  
  11. TARGET = JSONParser
  12. TEMPLATE = app
  13.  
  14.  
  15. SOURCES += main.cpp\
  16. widget.cpp
  17.  
  18. HEADERS += widget.h
  19.  
  20. FORMS += widget.ui

widget.h

Connect class QNetworkAccessManager , also declared in the header file SLOT o nResult(QNetworkReply * reply) , which will be parsed JSON file when receiving a response from the site with the contents of the file.

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5. #include <QNetworkAccessManager>
  6.  
  7. namespace Ui {
  8. class Widget;
  9. }
  10.  
  11. class Widget : public QWidget
  12. {
  13. Q_OBJECT
  14.  
  15. public:
  16. explicit Widget(QWidget *parent = 0);
  17. ~Widget();
  18.  
  19. private slots:
  20. // Обработчик данных полученных от объекта QNetworkAccessManager
  21. void onResult(QNetworkReply *reply);
  22.  
  23. private:
  24. Ui::Widget *ui;
  25. QNetworkAccessManager *networkManager;
  26. };
  27.  
  28. #endif // WIDGET_H

widget.cpp

The process is to create QJsonDocument object and write the contents of QNetworkReply response. Then pick up the document root of the root object that contains all three properties. After that, pick up titles for their property values. From the second property "employes" pick up the array with the names and surnames of members of the Department. All data is placed in the ui->textEdit .

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. #include <QJsonDocument>
  5. #include <QJsonObject>
  6. #include <QJsonArray>
  7. #include <QUrlQuery>
  8. #include <QNetworkReply>
  9. #include <QUrl>
  10.  
  11. Widget::Widget(QWidget *parent) :
  12. QWidget(parent),
  13. ui(new Ui::Widget)
  14. {
  15. ui->setupUi(this);
  16.  
  17. networkManager = new QNetworkAccessManager();
  18. // Connect networkManager response to the handler
  19. connect(networkManager, &QNetworkAccessManager::finished, this, &Widget::onResult);
  20. // We get the data, namely JSON file from a site on a particular url
  21. networkManager->get(QNetworkRequest(QUrl("http://www.evileg.ru/it_example.json")));
  22. }
  23.  
  24. Widget::~Widget()
  25. {
  26. delete ui;
  27. }
  28.  
  29. void Widget::onResult(QNetworkReply *reply)
  30. {
  31. // If there are no errors
  32. if(!reply->error()){
  33.  
  34. // So create an object Json Document, by reading into it all the data from the response
  35. QJsonDocument document = QJsonDocument::fromJson(reply->readAll());
  36.  
  37. // Taking from the document root object
  38. QJsonObject root = document.object();
  39. /* We find the object "departament", which is the very first in the root object.
  40.          * Use the keys() method gets a list of all objects and the first index
  41.          * Take away the name of the object on which we obtain its value
  42. * */
  43. ui->textEdit->append(root.keys().at(0) + ": " + root.value(root.keys().at(0)).toString());
  44.  
  45. // The second value prescribe line
  46. QJsonValue jv = root.value("employees");
  47. // If the value is an array, ...
  48. if(jv.isArray()){
  49. // ... then pick from an array of properties
  50. QJsonArray ja = jv.toArray();
  51. // Going through all the elements of the array ...
  52. for(int i = 0; i < ja.count(); i++){
  53. QJsonObject subtree = ja.at(i).toObject();
  54. // Taking the values of the properties and last name by adding them to textEdit
  55. ui->textEdit->append(subtree.value("firstName").toString() +
  56. " " +
  57. subtree.value("lastName").toString());
  58. }
  59. }
  60. // At the end we take away the property of the number of employees of the department and also to output textEdit
  61. ui->textEdit->append(QString::number(root.value("number").toInt()));
  62. }
  63. reply->deleteLater();
  64. }

Result

As a result of this code will have the following result, which is shown in the following image below.

Video

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup