-1

I want to write a sentence into a JSON file in Qt. I did it in python and it was quite easy, no need to convert the text into (value, key) pairs but in Qt what I search is only in this format. I wrote a piece of code that splits the sentence into strings and tries to convert the list of strings into the JSON array and then write it into a json file. The problem is that it compiles without error and makes a tmp.json file with a size of 1Kb but with no content inside.

    QFile f("PATH/tmp.json");
    QString str = "how are you do";
    f.open(QIODevice::ReadWrite);
    QJsonArray disk_array = QJsonArray::fromStringList(str.split(' '));
    QJsonDocument jsonDoc;
    jsonDoc.setArray(disk_array);
    f.write(jsonDoc.toJson());
    f.close();
4

1 回答 1

0

此代码执行此操作

 QFile  dat("tmp.json");

 dat.resize(0);

 QString str = "how are you do";
 QJsonDocument  doc;
 QJsonObject    obj;

 obj["tempText"] = str;

 doc.setObject(obj);
 QByteArray  data_json = doc.toJson();

 if (dat.open(QIODevice::WriteOnly | QIODevice::Text))
 {
    dat.write(data_json);
    dat.flush();
    dat.close();
 }

文件中的输出是这样的tmp.json

{
"tempText": "how are you do"
}
于 2021-06-24T20:42:44.717 回答