C++ – How to save and load a QJsonDocument to a file

c++, json, qt, qt5

I am trying to learn how to use JSON and the Qt JSON classes. For example I wnat to create a simple QJsonDocument, save it to a file, load it into a different QJsonDocument and compare results.

I managed to create a QJsonDocument. However there is no simple command in the QJsonDocument interface to save it to a file. The same goes for loading the document from a file.

#include <QJsonObject>#include <QJsonDocument>#include <QVariant>int main(){    QVariantMap map;    map.insert("integer", 1);    map.insert("double", 2.34);    map.insert("bool", QVariant(true));    map.insert("string", "word");    QJsonObject object = QJsonObject::fromVariantMap(map);    QJsonDocument document;    document.setObject(object);    // ?? save document to file    // ?? load file to document    return 0;}

This answer shows how to load the document by

  1. reading to a QFile
  2. converting QFile to a QString
  3. converting the QString to a QByteArray
  4. constructing the QJsonDocument from the QByteArray

Is there a more straightforward way to do this?

Best Solution

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.