0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

alright, looks like I've a mistake in reading my debugger. That was working all along it looks like I'm not pulling out the information correctly. Going to edit post quiet a bit.
And nevermind, just ran all the json["xx"].isXXX() and managed to figure out how to read the data back in.
Ok. Good to know that you fixed it.
Yea, didn't relize that QJsonObjects could nest. Was trying to read it as an array and was coming up empty every time
You can do something like: if(jsonDoc.object().find("XYZ").value().isArray()) { } else { }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.