Reputation: 15
Im trying to learn how to use JSON and Qt i have menaged and im having problem getting QJsonDocument from a file.The file opens correctly i can also see file's content with qDebug() but the QJsonDocument created from this file is always empty
if(stdButton==QDialogButtonBox::Ok)
{
qDebug()<<"accept button clicked";
QFile userList;
userList.setFileName("users.json");
userList.open(QIODevice::ReadOnly);
//using this qDebug i'm able to see files content
qDebug()<<QJsonDocument::fromJson(userList.readAll());
//but this QJsonDocument is always empty
QJsonDocument userDoc;
userDoc=QJsonDocument::fromJson(userList.readAll());
if(userDoc.isEmpty())
{
qDebug()<<"userDoc is empty";
}
qDebug()<<userDoc;
accept();
}
Upvotes: 0
Views: 1560
Reputation: 206577
//but this QJsonDocument is always empty QJsonDocument userDoc; userDoc=QJsonDocument::fromJson(userList.readAll());
That's because there is nothing to read from the file since you have read everything from it in the previous call to readAll()
.
You can store the data from userList.readAll()
and use it repeatedly.
QFile userList;
userList.setFileName("users.json");
userList.open(QIODevice::ReadOnly);
QByteArray data = userList.readAll();
qDebug()<<QJsonDocument::fromJson(data);
QJsonDocument userDoc;
userDoc=QJsonDocument::fromJson(data);
Upvotes: 1