Class Creation to create Json object in QT

Asked

Viewed 17 times

0

Good night! I am studying QT and would like to make a class (.h) to perform a request on a Rest server and create a json object for later query of keys and values. I am developing a program in conjunction with this API, I can already make the request, but I am not able to create the object to read in a QML file.

Here is a snippet of the header and cpp.

test. h

#ifndef TESTE_H
#define TESTE_H

#include <QObject>
#include <QtNetwork>

class Teste : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString usuario READ usuario WRITE setUsuario NOTIFY usuarioChanged)
    Q_PROPERTY(QString url READ url WRITE setUrl NOTIFY urlChanged)
    Q_PROPERTY(QString vtoken READ vtoken WRITE setVtoken NOTIFY vtokenChanged)

public:
    explicit Teste(QObject *parent = nullptr);
    QString usuario();
    QString url();
    QString vtoken();

signals:
    void usuarioChanged();
    void urlChanged();
    void vtokenChanged();

public slots:
    void setUsuario(QString);
    void setUrl(QString);
    void setVtoken(QString);
    void vAPI();
    void Resultado();

private:
    QString m_usuario;
    QString v_url;
    QString v_token;
    QString v_servidor = "http://localhost:8000/";
    QNetworkAccessManager* m_netManager;
    QNetworkRequest v_request;
    QNetworkReply *v_reply;
    QJsonObject v_json;

};

#endif // TESTE_H

cpp testing.

#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include "teste.h"

Teste::Teste(QObject *parent) : QObject(parent)
{
    m_netManager = new QNetworkAccessManager(this);
}

void Teste::vAPI()
{
    qDebug() << "Realizando request na API ...";
    v_request.setUrl(QUrl(v_url));
    v_reply = m_netManager->get(v_request);
    connect(v_reply, SIGNAL(finished()), this, SLOT(Resultado()));
}

void Teste::Resultado()
{
    if(!v_reply->error()){
        QJsonDocument document = QJsonDocument::fromJson(v_reply->readAll());
        QJsonObject json = document.object();
        foreach(const QString& key, json.keys()) {
            QJsonValue value = json.value(key);
            qDebug() << "Key = " << key << ", Value = " << value.toString();
        }
        QJsonValue v1 = document.object().value("detail");
        qDebug() << v1;
    }

After the request, in the Result slot I can read the json, but I don’t know how to export this json to be read in a QML.

Example, after a click of a button he makes the request, creates the object and does the verification within that object of a certain key and a certain value.

If you could give me some light, I’d really appreciate it!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.