converting QList<QUuid> to QJsonArray
-
Hi all -
I need to convert a list of QUuids into a QJsonArray for insertion into a QJsonObject. Here's what I've tried:
typedef QList<QUuid> equipmentUuidList; QJsonValue qjv; QJsonArray qja; equipmentUuidList list; for (auto &e: list) { QVariant qv = QVariant::fromValue(e); qjv = qv.toJsonValue(); // this line isn't working. qja.append(qjv); }
but the qjv is assigned Null. Can someone see what I'm doing wrong?
Thanks...
-
Hi @mzimmers,
The problem is that the
qv
metatype isQUuid
, but theQVariant::toJsonValue()
docs say:Returns the variant as a
QJsonValue
if the variant hasuserType()
QJsonValue
; otherwise returns a default constructedQJsonValue
.So, for example:
typedef QList<QUuid> equipmentUuidList; QJsonValue qjv; QJsonArray qja; const equipmentUuidList list { QUuid::createUuid(), QUuid::createUuid(), QUuid::createUuid() }; qDebug() << "list:" << list; for (auto &e: list) { QVariant qv = QVariant::fromValue(e); qDebug() << "qv:" << qv.typeName() << qv; ///< Type is QUuid. qjv = qv.toJsonValue(); ///< null, because qv is not a JSON type. qDebug() << "qjv:" << qjv; qja.append(qjv); } qDebug() << "qja:" << qja;
Outputs:
list: QList(QUuid("{f1642ef0-0c4b-48a1-953f-0278e90b6393}"), QUuid("{eb793ede-712c-44e6-8162-8c52af57c383}"), QUuid("{dfee85fe-c0cb-46eb-9d64-6505ddcbca07}")) qv: QUuid QVariant(QUuid, QUuid("{f1642ef0-0c4b-48a1-953f-0278e90b6393}")) qjv: QJsonValue(null) qv: QUuid QVariant(QUuid, QUuid("{eb793ede-712c-44e6-8162-8c52af57c383}")) qjv: QJsonValue(null) qv: QUuid QVariant(QUuid, QUuid("{dfee85fe-c0cb-46eb-9d64-6505ddcbca07}")) qjv: QJsonValue(null) qja: QJsonArray([null,null,null])
The JSON standard does not have any UUID type - the only way to represent UUIDs in JSON is via strings (with optional JSON Schemas to enforce a pattern). So just convert the UUID to string directly, like:
typedef QList<QUuid> equipmentUuidList; QJsonArray qja; const equipmentUuidList list { QUuid::createUuid(), QUuid::createUuid(), QUuid::createUuid() }; qDebug() << "list:" << list; for (const auto &e: list) { qja.append(e.toString()); } qDebug() << "qja:" << qja;
Outputs:
list: QList(QUuid("{02a6b10a-0c52-4208-a4c4-d669b621a3cb}"), QUuid("{367cead7-7229-43cb-8176-b08365e83fc9}"), QUuid("{3117ed2a-f7cc-4563-b4af-4af52947e902}")) qja: QJsonArray(["{02a6b10a-0c52-4208-a4c4-d669b621a3cb}","{367cead7-7229-43cb-8176-b08365e83fc9}","{3117ed2a-f7cc-4563-b4af-4af52947e902}"])
Cheers.
-
@Paul-Colby oh, of course...this is what happens when I work too late at night -- I make silly mistakes. Thanks for the help.
-