1

I need to do a request in Qt/c++ to get a JSON file, and then parse it and fill my object.

The request seems good, and "it looks like" my QtNetworkReply reply is filled.

But after many attempts, I still don't understand how can I convert it into a QbyteArray (I don't even know if it's the right thing to do...), for being able to convert it into my class.

Here's my code :

QNetworkAccessManager networkManager;
QUrl url("https://api.myjson.com/bins/uvki"); //url from a free json host
QNetworkRequest request;enter code here
request.setUrl(url);
QNetworkReply* reply = networkManager.get(request);
QByteArray reponse;

if (reply == NULL)
{
    std::cout << "Damn" << std::endl;
    exit(2);
}
reponse = reply->readAll();
if (reponse == NULL)
{
    std::cout << "i hate you" << std::endl;
    exit(1000);
}

I might have done some stupid stuff, I only have 2 days of c++

Can you tell me how I can convert my "reply" into my "reponse"?

Jonnus
  • 2,988
  • 2
  • 24
  • 33

2 Answers2

2

The answer provided by @MichaelBoone is correct.

In addtion, with C++11, you can simplify the code by using Qt 5's QObject::connection syntax and a lambda function

QJsonDocument document;
QNetworkReply* pReply = networkManager.get(request);

connect(reply, &QNetworkReply::finished, [=](){  

  // the reply will return here
  QByteArray response = pReply->readAll();
  document = QJsonDocument::fromBinaryData(response);

});

Qt 5's connections syntax has the advantage of compile-time verification of the connection, which is not present when using the SIGNAL and SLOT macros.

Community
  • 1
  • 1
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
1

You have to connect the finished() signal from reply object, or from the NetworkManager to get the results. You will also need to make *reply a class member, or you won't be able to access it within your handler SLOT.

QNetworkReply* reply = networkManager.get(request);
connect(reply, SIGNAL(finished()), this, SLOT(YourFunctionHere()));

void YourFunctionHere(){
    //handle the data
}

QNetworkReply is a non-blocking function, like most QT Network functions, it is asynchronous. By the time you are reaching your conditional if statement to check the reply, it hasn't yet received a response from the network.

As far as handling the download afterwards, you are correct in using a QByteArray.

QByteArray QIODevice::readAll()

This is an overloaded function.

Reads all available data from the device, and returns it as a QByteArray.

From there you use QJsonDocument.

QJsonDocument QJsonDocument::fromBinaryData(const QByteArray & data, DataValidation validation = Validate)

Creates a QJsonDocument from data.

Edit - Sorry I don't have the reputation to comment, but I feel The answer provided by TheDarkKnight lends itself better to the one-off nature of a "Reply" and is less encumbered by having to create a new slot. lambdas are just very cool, and the compile time verification is nice.

Michael B.
  • 145
  • 1
  • 10