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

时间:2018-04-04 01:10:26

标签: c++ json qt c++11 qt5.10

我正在尝试从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按名称获取的命名数组。关于如何直接使用QJsonArray或与QJsonDocument::fromJson()一起使用返回数据的任何提示?

2 个答案:

答案 0 :(得分:4)

QJsonDocument有一个名为array()的成员,该成员会返回文档中包含的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();
}

答案 1 :(得分:0)

您尝试过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
        }]