1

I have a QString that I need to insert it to a QJsonArray. The problem is that the string is inserrted as it is and the escape sequences doesnot work.

    QString fmt = QString("{\n \"%1\":\"%2\"\n}").arg(id,name);
    QJsonValue qjv(fmt);
    labellist.insert(lSize, qjv);

Here, the qstring is populated with the values from "id" and "name" (these are also QString) and then inserted to qjsonarray. The labellist here is a QJsonArray. The inputs to the QString are say for example "55" and "ggg". When I print the qstring like

    qDebug().noquote() << fmt;

it gives me

    {
     "55":"ggg"
    }

but if I insert it to the labellist and print the labellist it gives:

    QJsonArray([{"121":"fuu"},{"122":"cat"},{"123":"dog"},"{\n \"55\":\"ggg\"\n}"])

The format of the QJsonvalues in the above array is lost.

How to decode the string to preserve the format and make the escape sequences work?

4

1 回答 1

1

我会使用QJsonDocument静态方法fromJson(),如下所示:

  QString fmt = QString("{\n \"%1\":\"%2\"\n}").arg("id","name");

  QJsonDocument doc = QJsonDocument::fromJson(fmt.toLocal8Bit());
  QJsonObject obj = doc.object();

  QJsonArray array;
  array.append(obj);

  qDebug() << array;
于 2017-11-02T18:49:57.680 回答