How to save and load a QJsonDocument to a file? How to save and load a QJsonDocument to a file? json json

How to save and load a QJsonDocument to a file?


Personally, I think that code [that you linked to] looks a bit messy. Warning: head compiled code follows.

QJsonDocument loadJson(QString fileName) {    QFile jsonFile(fileName);    jsonFile.open(QFile::ReadOnly);    return QJsonDocument().fromJson(jsonFile.readAll());}void saveJson(QJsonDocument document, QString fileName) {    QFile jsonFile(fileName);    jsonFile.open(QFile::WriteOnly);    jsonFile.write(document.toJson());}

This may not be perfect: it assumes QFile instead of QIODevice, but if you're dealing with only local files maybe it won't matter. You can then use these functions instead of repeating the Json load/save code everytime you need to load/save Json.


No need for converting to string and back. With QSettings and QVariant classes you can easily do that. Create QVariant object from QJsonDocument and save it with QSettings. Look at functions QJsonDocument::fromVariant and QJsonDocument::toVariant. Combine them with QSettings class and specifically void QSettings::setValue ( const QString & key, const QVariant & value ) method, that works well with QVariant and that's it.

Also QSettings class has this constructor QSettings::QSettings ( const QString & fileName, Format format, QObject * parent = 0 ) that would allow you to set path to the file - fileName variable