我正在尝试使用Qt为online dictionary site编写一个桌面客户端。我陷入了有关JSON的问题。
http://ac.tureng.co/?c=?&t=expensive
?(["expensive","expensive habits","expensive medical equipment","expensive question","expensive watch","expensive-looking","expensively","expensiveness"]);
我认为来自上述地址的数据是JSON数组。 json.org具有以下描述:
数组是值的有序集合。数组以[ (左括号)并以](右括号)结尾。值是分开的 由,(逗号)。*
如果写入的是字符串而不是第一个问号,则根据JSON Formatter的有效JSON:
a([
"expensive",
"expensive habits",
"expensive medical equipment",
"expensive question",
"expensive watch",
"expensive-looking",
"expensively",
"expensiveness"
]);
但是对于JSONLint网站而言,此更改还不够:
["expensive", "expensive habits", "expensive medical equipment", "expensive question", "expensive watch", "expensive-looking", "expensively", "expensiveness"]
我想使用此处的数据在用户输入时向用户显示建议。目前,我无法提取JSON,因此通过将其用作纯文本来达到所需的行为。有没有办法通过解析JSON正确地做到这一点?
到目前为止我写的代码是:
QString turengOneriMetin = QString("http://ac.tureng.co/?c=?&t=%1").arg(arg1);
QUrl turengOneri(turengOneriMetin);
QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(turengOneri));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));
event.exec();
QString content = response->readAll();
content.replace(0,1,"a");
content = content.replace("a([", "").replace("]);", "").replace("\"","");
QStringList wordList;
wordList << content.split(",");
ui->label->setText(content);
// https://stackoverflow.com/questions/24248606/how-to-accomplish-drop-down-word-suggestions-in-qt
QCompleter *completer = new QCompleter(wordList, this);
completer->setCaseSensitivity(Qt::CaseInsensitive);
ui->lineEdit->setCompleter(completer);
更新:在答案和other resources的帮助下正确接收了JSON之后,我用下面的代码完成了我想要的工作:
QJsonDocument document = QJsonDocument::fromJson(content.toUtf8());
QJsonArray documentArray = document.array();
QStringList wordList;
for (const QJsonValue &i : documentArray)
{
//qInfo() << i.toString() << endl;
wordList << i.toString();
}