Reputation: 5747
I have the following:
QString notebookid = ui->notebookid->toPlainText();
QString tagid = ui->tagid->toPlainText();
QString userid = ui->userid->toPlainText();
QString subject = ui->subject->toPlainText();
QString comment = ui->comment->toPlainText();
I need to turn them into JSON, where the key is the notebookid, tagid, etc and the value is in the ui->notebookid, etc.
What's the best way to go about doing this?
Thanks.
Upvotes: 0
Views: 4876
Reputation: 98505
In Qt 5, you can use QJsonObject
. One way is to explicitly select the controls to serialize:
QJsonObject MyDialog::serialize() const {
QJsonObject json;
json.insert("notebookid", ui->notebookid->toPlainText());
...
return json;
}
Another way is to have a generic serializer that uses the Qt's metadata. Each named control's user property is then serialized:
QJsonObject serializeDialog(const QWidget * dialog) {
QJsonObject json;
foreach (QWidget * widget, dialog->findChildren<QWidget*>()) {
if (widget->objectName().isEmpty()) continue;
QMetaProperty prop = widget->metaObject()->userProperty();
if (! prop.isValid()) continue;
QJsonValue val(QJsonValue::fromVariant(prop.read(widget)));
if (val.isUndefined()) continue;
json.insert(widget->objectName(), val);
}
return json;
}
You can convert QJsonDocument
to text as follows:
QJsonDocument doc(serializeDialog(myDialog));
QString jsonText = QString::fromUtf8(doc.toJson());
Unfortunately, Qt 5's json code requires a bunch of changes to compile under Qt 4.
Upvotes: 0
Reputation: 396
I'll answer this based on the fact that you were using Qt 4.8 and would not have the QJsonObject available from Qt5.
I use QJSON for exactly this. It's an easy-to-use library using QVariants to parse and serialize the data.
This would be how you'd turn your data into json using QJSON:
QVariantMap jsonMap;
jsonMap.insert("notebookid", notebookid);
jsonMap.insert("tagid", tagid);
jsonMap.insert("userid", userid );
jsonMap.insert("subject", subject );
jsonMap.insert("comment", comment);
QJson::Serializer serializer;
bool ok;
QByteArray json = serializer.serialize(jsonMap, &ok);
assert (ok);
Upvotes: 1