c++ - 使用 Qt 解析 JSON 数组

标签 c++ json qt api dictionary

我正在尝试使用 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 有以下描述:

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).*



也是根据 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();
}

最佳答案

我认为 URL 应该是 - http://ac.tureng.co/?t=expensive

在这种情况下,您将获得有效的 JSON。

关于c++ - 使用 Qt 解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52806006/

相关文章:

c++ - Cmake,在/usr/local/include 中找到头文件,在/usr/local/lib 中找到库

javascript - 从 jQuery 中读取只有一个对象的 JSON 数组的值

json - 如何使用 jq 从子数组创建具有任意键的对象?

javascript - 将 JSON 转换为 HTML : Uncaught TypeError: json. forEach 不是函数

c++ - 在 Visual Studio 上编译 qt 示例时出现链接错误

c++ - Qt 中的 SQLite 数据库

c++ - 是否可以重新定义析构函数?

python - 为什么 (0.0006*100000)%10 是 10

c++ - 构造函数参数的 SFINAE

QT wayland 无法创建显示(没有这样的文件或目录)