Dave851
Dave851

Reputation: 5

Qt parsing json using network response binary

Alright, I found something I just don't understand. I am making a request to a web service using QtNetworkManager. For some reason I can't seem to go from the network response to a jsondoc directly, I have to cast it into a string and then BACK into uft8?

void WebAPIengine::handleNetworkData(QNetworkReply *networkReply)
{

//No network error
if (!networkReply->error()){

    //Cast to string
    QString strReply = (QString)networkReply->readAll();

    //This works, jsonDoc will have the json response from webpage
    QJsonDocument jsonDoc = QJsonDocument::fromJson(strReply.toUtf8());

    //This doesn't work, networkReply->readAll() is said to return a QByteArray. 
    QJsonDocument jsonDoc2 = QJsonDocument::fromBinaryData(networkReply->readAll());
    QJsonObject jsonObj = jsonDoc.object();
    data = jsonObj;
}
//Network error
else{
    data["Error"] = "WebAPIengine::handleNetworkData()";
}

Now I can not understand why jsonDoc is working and jsonDoc2 is not. Can someone explain?

Upvotes: 0

Views: 1271

Answers (1)

Nithish
Nithish

Reputation: 1640

Once you do a QNetworkReply->readAll(), the QNetworkReply object will be empty. So if you call the QNetworkReply->readAll() method again, you will not get anything.

Moreover I don't understand why you are converting the QByteArray returned by QNetworkReply->readAll() into a QString and then converting it back to QByteArray(by calling QString::toUtf8()) to give it to the QJsonDocument::fromJson function.

You can try doing this:

QByteArray temp = newReply->readAll();
QJsonDocument  jsonDoc = QJsonDocument::fromJson(temp); // This should work

Also make sure to know what the content of the JSon document is, i.e. if it is a map (QJsonObject), array(QJSonArray), array of maps or map with an array as value.

Upvotes: 2

Related Questions