Home > database >  Converting QMap<QString, QString> to Json string results empty
Converting QMap<QString, QString> to Json string results empty

Time:12-24

I have a function defined and used as this:

// usage:
QMap<QString, QString> map = ...;
foo(map);

// defination:
QString stringMapToJson(const QMap<QString, QString>& arg) {
    QVariant v = QVariant::fromValue(arg);
    JsonDocument doc = QJsonDocument::fromVariant(v);
    ...
}

Then I realized v is empty.

  1. Is there a method to convert QMap<String, QString> to QMap<String, QVariant>, so above v could be valid?
  2. Why above v is empty? I read people were saying QVariant and qMetaData, I don't understand given the following valid, why QString have a qMetaData problem:
QString s = "";
QVariant v = s;

(A Java programmer starts her pleasant C journey.)

Thanks.

CodePudding user response:

There are 2 ways to do this. The first is to convert your map to a QMap<QString, QVariant> like you mentioned:

QByteArray stringMapToJson1(const QMap<QString, QString>& arg)
{
    QVariantMap vmap;
    for(auto it = arg.cbegin(); it != arg.cend();   it)
    {
        vmap.insert(it.key(), it.value());
    }
    const QVariant v = QVariant::fromValue(vmap);
    const QJsonDocument doc = QJsonDocument::fromVariant(v);
    return doc.toJson();
}

Alternatively, you can build the json object directly from the map. In this case it's the same amount of code:

QByteArray stringMapToJson2(const QMap<QString, QString>& arg)
{
    QJsonObject jObj;
    for(auto it = arg.cbegin(); it != arg.cend();   it)
    {
        jObj.insert(it.key(), it.value());
    }
    QJsonDocument doc;
    doc.setObject(jObj);
    return doc.toJson();
}

This seems like a stylistic choice and I am unsure which would be faster. Both produce the same output.

One thing to note: The conversion from QString to QVariant is predefined in Qt, so the first method works fine. For objects of your own classes you would have to register that type and provide a suitable conversion which can be a bit tough to get right. In the second method you could do this conversion inline in the loop.

  •  Tags:  
  • qt
  • Related