mercredi 22 avril 2015

How to parse JSON for Qt Quick?

I am trying to do a simple programming to parse JSON message value from web to Qt Quick.

The JSON message would like to parse:

         "id": 2,
         "name": "yahoo",
         "link": "",
         "created_by": "superadmin",
         "create_time": "2015-03-12 14:45:21"
         "id": 3,
         "name": "Google",
         "link": "",
         "created_by": "superadmin",
         "create_time": "2015-03-12 14:45:41"
         "id": 4,
         "name": "PS",
         "link": "",
         "created_by": "superadmin",
         "create_time": "2015-03-24 11:57:21"

The following is the Qt code main.cpp to try to parse these data:

#include <QGuiApplication>
#include <QStringList>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptValueIterator>
#include <qqmlengine.h>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>

class Jsondata : QObject{
    QStringList datalist;
        void onResult (QNetworkReply*);
        QStringList datalistmethod() {
            return datalist;

void Jsondata::onResult(QNetworkReply* reply)
    //if (m_currentReply->error() != QNetworkReply::NoError)
    //  return;  // ...only in a blog post

    QString data = (QString) reply->readAll();

    QScriptEngine engine;
    QScriptValue result = engine.evaluate(data);

    // Now parse this JSON according to your needs !
    QNetworkAccessManager networkManager;

    QUrl url("http://***/api/web/v1/links");
    QNetworkRequest request;

    QObject::connect(&networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onResult(QNetworkReply*))); //Error. 
    networkManager.get(request);  // GET

    QString data = (QString) reply->readAll();

    QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
    QJsonObject jsonObject = jsonResponse.object();
    QJsonArray jsonArray = jsonObject["name"].toArray();

    foreach (const QJsonValue & value, jsonObject) {
        QJsonObject obj = value.toObject();

int main(int argc, char ** argv)
    QGuiApplication app(argc, argv);

    Jsondata jsondata;

    QStringList datalist;
    datalist = jsondata.datalistmethod();

    QQuickView view;
    QQmlContext *ctxt = view.rootContext();
    ctxt->setContextProperty("myModel", QVariant::fromValue(datalist));


    return app.exec();


import QtQuick 2.0

ListView {
    width: 100; height: 100

    model: myModel
    delegate: Rectangle {
        height: 25
        width: 100
        Text { text: modelData }

Results in: onResult not called. so no datalist returned

I don't have knowledge on this QObject::connect and don't know what wrong. I would appreciate it if you could help me to fix this bug.

Aucun commentaire:

Enregistrer un commentaire