Im trying to make the start of a wrapper class for json in qt 5.1 and i'm working on a function which which will check if the var inputted is a QVariantMap or just a QVariant and everything works well till i go the second level of the muli dimen array. here is my array structure and class code.
JsonHelper jh;
QVariantMap obj = jh.getJsonObjectVarientMap(data);
This causes me the problems, when i just use "obj" or "obj["1"]" there is no issues, only when i
// obj["4"]["3"] this causes the problems
qDebug() << "Your returned val is : " << jh.keySearchVal(obj["4"]["3"],arr_index_txt);
QMap<QString,QVariant> mp = obj["4"].toMap();
foreach(QString key,mp.keys())
{
// this works ok
qDebug() << "key : " << key << " : val : " << mp[key];
}
QVariantMap JsonHelper::getJsonObjectVarientMap(QString in)
{
QJsonDocument d = QJsonDocument::fromJson(in.toUtf8());
return d.object().toVariantMap();
}
QVariant JsonHelper::keySearchVal(QVariant source, QString key)
{
QString type(source.typeName());
if(type=="QVariantMap")
{
QMap<QString, QVariant> map = source.toMap();
foreach(QString key_inner,map.keys())
{
QVariant in = map[key_inner];
if(key_inner==key)
{
return getVariantVal(in);
}
}
}
return "";
}
QVariant JsonHelper::keySearchVal(QVariantMap source, QString key)
{
foreach(QString key_inner,source.keys())
{
if(key_inner==key)
{
return source[key_inner];
}
}
return "";
}
QVariant JsonHelper::getVariantVal(QVariant in)
{
qDebug() << "from variant";
QString type(in.typeName());
if(type=="QVariantMap")
{
return in.toMap();
}
return in;
}
That is invalid because
QVariant
does not have an operator[] overload. That is also what the compiler is trying to tell you with this:You will need to convert any nested QVariant explicitly to QVariantMap if that is the underlying data type. See the following method for details:
It is not the main point, but you also have two further issues:
You seem to use the word Varient as opposed to Variant.
Your code lacks error checking and reporting for conversions, etc.