2

I have a QMap object and I would like to convert it to JSON. I am confused how I would accomplish this.

I read QT documentation saying that I can use QDataStream to convert QMap to JSON, but QDataStream seems to convert files: http://doc.qt.io/qt-4.8/datastreamformat.html

// c++
QMap<QString, int> myMap;
Jon
  • 8,205
  • 25
  • 87
  • 146
  • You open a `QFile`, use that as an argument to construct a new `QDataStream`, and then use the `<<` operator to serialize `myMap`. – rwols Apr 19 '17 at 00:00

2 Answers2

12

It would be easiest to convert the map to QVariantMap which can automatically be converted to a JSON document:

QMap<QString, int> myMap;
QVariantMap vmap;

QMapIterator<QString, int> i(myMap);
while (i.hasNext()) {
    i.next();
    vmap.insert(i.key(), i.value());
}

QJsonDocument json = QJsonDocument::fromVariant(vmap);

The same thing can be used to create a QJsonObject if you want, via the QJsonObject::fromVariant() static method. Although for QJsonObject you can skip the conversion to variant map step and simply populate the object manually as you iterate the map:

QMap<QString, int> myMap;
QJsonObject json;

QMapIterator<QString, int> i(myMap);
while (i.hasNext()) {
    i.next();
    json.insert(i.key(), i.value());
}    
dtech
  • 47,916
  • 17
  • 112
  • 190
1

If you are using Qt 5.5 or higher you could use QJsonDocument::fromVariant, your map could be converted easily to a QVariantMap. If not, try QJson

For your purpose, you are looking for QMAP serialization, see this link: Serialization Qt. Try to set up the constructor with a QByteArray, something like this:

   QByteArray serializeMap(const QMap<QString, int>& map) {
      QByteArray buffer;
      QDataStream stream(&buffer, QIODevice::WriteOnly);
      out << map;
      return out;
   }

That's, will serialize your map in a QByteArray wich could be easily converted to a QString or std::string.

mohabouje
  • 3,867
  • 2
  • 14
  • 28