【问题标题】:QJsonDocument - getting values indentedQJsonDocument - 获取缩进的值
【发布时间】:2015-03-30 18:42:32
【问题描述】:

我有一个这样的 Json 响应:

{
  "data": [
    {
      "id": "someID", 
      "participants": {
        "data": [
          {
            "id": "idN1"
          }, 
          {
            "id": "idN2"
          }
        ]
      }
    },
    {
      "id": "someID", 
      "participants": {
        "data": [
          {
            "id": "idN3"
          }, 
          {
            "id": "idN4"
          }
        ]
      }
    }
  ]
} 

我想在“参与者”中获取第二个 id 数组(缩进最多的数组)。

我的代码正在获取第一个 id 值的值,而不是参与者内部的值。这是我的代码:

QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["data"].toArray();

foreach (const QJsonValue & value, jsonArray) {
    QJsonObject obj = value.toObject();

    if (obj["id"].toString()!=selfID) {
        myIdList.append(obj["id"].toString());
    }
}

我想知道如何摆脱缩进较少的 id 并将缩进最多的 id 放入 myIdList。

有一个漂亮的代码!

【问题讨论】:

    标签: qt qjson qjsonobject


    【解决方案1】:

    给你

    #include <QList>
    #include <QFile>
    
    #include <QDebug>
    #include <QJsonArray>
    #include <QJsonDocument>
    #include <QJsonObject>
    
    int main(int argc, char *argv[])
    {
        QFile file("/your/json-file/bla.json");
        file.open(QIODevice::ReadOnly);
    
        QString data = file.readAll();
        QString selfID = "2";
    
        QList<QString> myIdList = QList<QString>();
    
        QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
        QJsonObject jsonObject = jsonResponse.object();
        QJsonArray jsonArray = jsonObject["data"].toArray();
    
        foreach (const QJsonValue & value, jsonArray) {
            QJsonObject obj = value.toObject();
            QString id = obj["id"].toString();
    
            if (id != selfID)
            {
                QJsonObject participants = obj["participants"].toObject();
                QJsonArray participants_data = participants["data"].toArray();
    
                foreach (const QJsonValue &data_element, participants_data)
                {
                    QString inner_id = data_element.toObject()["id"].toString();
                    myIdList.append(inner_id);
                }
            }
        }
        qDebug() << myIdList;
    
        return 0;
    }
    

    【讨论】:

    • 完美运行。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    相关资源
    最近更新 更多