【发布时间】:2019-03-19 05:57:18
【问题描述】:
我正在尝试使用 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();
}
【问题讨论】:
-
此站点是否有某种 API 文档?我不会在没有验证的情况下假设这是 JSON 格式的兔子洞。
-
为什么
?c在你的网址中? -
@MrEricSir 没有可用的 API 文档。但在 GitHub 中,有人可以看到类似的客户端如何使用 API。
-
@eyllanesc 你是对的,这里没用,没有它,链接给出了一个有效的 JSON。我去看看能不能解析这个结果。
标签: c++ json qt api dictionary