从 Qt 中的 Web 服务解析未命名的 JSON 数组

Parse unnamed JSON Array from a web service in Qt

我正在尝试从 Web 服务解析此 JSON。

  [
      {
        "word": "track",
        "score": 4144
      },
      {
        "word": "trail",
        "score": 2378
      },
      {
        "word": "domestic dog",
        "score": 51
      },
      {
        "word": "dogiron"
      }
  ]

当我如下所示注销来自 API 调用的响应作为 QString 时,结果很好,但所有引号都已转义,因此无法使其成为有效的 JSON:

QString response = (QString) data->readAll();
qDebug() << "Return data: \n" << response;

到目前为止我看到的示例(例如 Parse jsonarray?)仅解析命名数组,它们按名称从 QJsonObject 中获取。关于如何在 return 数据上直接使用 QJsonArray 或与 QJsonDocument::fromJson() 一起使用的任何提示?

QJsonDocument 有一个名为 array() 的成员,returns QJsonArray 包含在文档中。

例如:

QFile file("main.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray jsonData = file.readAll();
file.close();

QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(jsonData, &parseError);

if (parseError.error != QJsonParseError::NoError)
{
    qDebug() << "Parse error: " << parseError.errorString();
    return;
}

if (!document.isArray())
{
    qDebug() << "Document does not contain array";
    return;
}

QJsonArray array = document.array();

foreach (const QJsonValue & v, array)
{
    QJsonObject obj = v.toObject();
    qDebug() << obj.value("word").toString();
    QJsonValue score = obj.value("score");
    if (!score.isUndefined())
        qDebug() << score.toInt();
}

你试过 ThorsSerializer 了吗?

代码

#include "ThorSerialize/JsonThor.h"
#include "ThorSerialize/SerUtil.h"
#include <sstream>
#include <iostream>
#include <string>



struct MyObj
{
    std::string word;
    int         score;
};
ThorsAnvil_MakeTrait(MyObj, word, score);

用法示例:

int main()
{
    using ThorsAnvil::Serialize::jsonImport;
    using ThorsAnvil::Serialize::jsonExport;

    std::stringstream file(R"(
    [
      {
        "word": "track",
        "score": 4144
      },
      {
        "word": "trail",
        "score": 2378
      },
      {
        "word": "domestic dog",
        "score": 51
      },
      {
        "word": "dogiron"
      }
    ])");

    std::vector<MyObj>   data;
    file >> jsonImport(data);


    std::cout << data[1].score << " Should be 2378\n";
    std::cout << "----\n";
    std::cout << jsonExport(data) << "\n";
}

输出:

2378 Should be 2378
----
 [
        {
            "word": "track",
            "score": 4144
        },
        {
            "word": "trail",
            "score": 2378
        },
        {
            "word": "domestic dog",
            "score": 51
        },
        {
            "word": "dogiron",
            "score": -301894816
        }]