【问题标题】:Turn QString to JSON将 QString 转为 JSON
【发布时间】:2014-01-16 23:08:54
【问题描述】:

我有以下几点:

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();

我需要把它们转成JSON,其中key是notebookid、tagid等,value在ui->notebookid等中

最好的方法是什么?

谢谢。

【问题讨论】:

    标签: json qt qstring


    【解决方案1】:

    我将根据您使用的是 Qt 4.8 并且不会从 Qt5 获得 QJsonObject 的事实来回答这个问题。

    我正是为此使用QJSON。这是一个易于使用的库,使用 QVariants 来解析和序列化数据。

    这将是您使用 QJSON 将数据转换为 json 的方式:

    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);
    

    【讨论】:

      【解决方案2】:

      在 Qt 5 中,您可以使用QJsonObject。一种方法是显式选择要序列化的控件:

      QJsonObject MyDialog::serialize() const {
        QJsonObject json;
        json.insert("notebookid", ui->notebookid->toPlainText());
        ...
        return json;
      }
      

      另一种方法是拥有一个使用 Qt 元数据的通用序列化程序。然后序列化每个命名控件的用户属性:

      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;
      }
      

      您可以将QJsonDocument 转换为文本,如下所示:

      QJsonDocument doc(serializeDialog(myDialog));
      QString jsonText = QString::fromUtf8(doc.toJson());
      

      不幸的是,Qt 5 的 json 代码需要大量更改才能在 Qt 4 下编译。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2019-12-23
      • 2011-08-21
      • 2012-04-01
      相关资源
      最近更新 更多