QJsonArray.toArray() then to QStringList ?
-
wrote on 7 May 2021, 14:10 last edited by
I have a JSON array in a MariaDB record, I want to convert this to a QStringList, so far:
QJsonObject::iterator itOption = objJSON.find(scszOption); ... QStringList slstOptions = itOption.value().toArray().toVariantList();
How do I convert from QVariantList to an instance of QStringList?
-
I have a JSON array in a MariaDB record, I want to convert this to a QStringList, so far:
QJsonObject::iterator itOption = objJSON.find(scszOption); ... QStringList slstOptions = itOption.value().toArray().toVariantList();
How do I convert from QVariantList to an instance of QStringList?
-
@SPlatten
QVariantList
is aQList<QVariant>
. Iterate theQVariant
elements. There isQVariant::toString()
, orQVariant::toStringList()
if each individual variant is itself a list.wrote on 7 May 2021, 14:34 last edited by SPlatten 5 Jul 2021, 14:36@JonB said in QJsonArray.toArray() then to QStringList ?:
QVariant::toStringList()
That doesn't appear to be available in Qt 5.9.2, only toStdList. However...I think I've got it:
QVariantList vlstOptions = itOption.value().toArray().toVariantList(); QStringList slstOptions = vlstOptions.value_type.toStringList();
-
wrote on 7 May 2021, 14:40 last edited byThis post is deleted!
-
@JoeCFD , thank you, I just put together:
foreach( QVariant vItem, vlstOptions ) { slstOptions << vItem.toString(); }
-
@SPlatten for() is better than foreach and you may need to check if qvariant is valid. <== no check is needed. If it is invalid, toString() returns empty string.
wrote on 7 May 2021, 15:30 last edited by@JoeCFD , in the end I found a better solution:
QString strOption(itOption.value().toString()); QJsonDocument docJSON(QJsonDocument::fromJson(strOption.toLatin1())); QStringList slstOptions(docJSON.toVariant().toStringList());
3/7