Solved Getting a JSON string from PHP
-
I can't seem to covert a JSON string.
I am getting my JSON string from a PHP file.
Here's my code:void MainWindow::replyFinished(QNetworkReply *reply)
{
QMessageBox::information(this, "status", reply->readAll()); //Outputs a correct JSON string
qDebug() << reply->readAll(); //Outputs an empty string
QByteArray jsonData = reply->readAll();
if (jsonData.isEmpty()) {
qDebug() << "Empty"; //This output is executed
}
else
qDebug() << jsonData;QJsonDocument doc; QJsonParseError parseError; doc.fromJson(jsonData, &parseError); qDebug() << parseError.error; //Error outputs: 5
}
I guess reply->readAll() is wrong since QDebug doesn't work with it. What should I use instead?
-
Hi, welcome to devnet.
Your problem is calling readAll() repeatedly. The reply object is a stream. Once you readAll() from it it's empty. So read it once to some byte array and use that instead of calling readAll() again, as there's nothing left to read.
Also, you should call
reply->deleteLater()
after you're done with the reply, because you're leaking memory. -
@Chris-Kawa thanks for replying. I stored the reply->readAll() in a QByteArray but now I am facing another problem. I cannot convert the JSON string to an object.
Here's my code:
void MainWindow::replyFinished(QNetworkReply *reply)
{
QByteArray jsonData = reply->readAll();
if (jsonData.isEmpty()) {
qDebug() << "Empty";
}
else
qDebug() << jsonData;QJsonDocument doc; QJsonParseError parseError; doc.fromJson(jsonData, &parseError); qDebug() << parseError.error; if (!doc.isObject()) { qDebug() << "Document is not an object"; //This is executed. } QJsonObject object = doc.object(); QJsonValue jsonValue = object.value("players");
}
The JSON string that my PHP file outputs looks like this:
[{"players":"1","lastUpdate":"1446911197"}]However, QByteArray is:
"[{"players":"1","lastUpdate":"1446911197"}] \n"Is the "\n" normal?
-
Hi and welcome to devnet,
fromJson is a static function returning a QJsonDocument, you're using it wrongly. Currently your doc object is just empty.
Note that the json you have doesn't contain an object but an array.
-
@SGaist said:
hat the js
Okay, I used it correctly and made myself a QJsonArray. But what do I do now? How do I get values from it?
QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError); qDebug() << parseError.error; QJsonArray theArray = doc.array();
-
You have an array of one element so your can do something like:
QJsonArray array = jsondoc.array(); QVariant firstElement = array.at(0).toVariant(); QVariantMap variantMap = firstElement.toMap(); int players = variantMap["players"].toInt();
-
@SGaist Thank you, it worked :)
-
You're welcome !
Since it's working now, please mark the thread as solved using the "Topic Tool" button so other forum users may know a solution has been found :)