【问题标题】:how to decode json in qt如何在qt中解码json
【发布时间】:2014-06-20 17:34:28
【问题描述】:

我想用 qt 解码下面的 json:

{
 "user": {
  "name": "string"
 }
}

我试图用这段代码来做,但不起作用:

QJsonDocument jsonResponse = QJsonDocument::fromJson(result.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["user"].toArray();
foreach (const QJsonValue & value, jsonArray)
        {
            QJsonObject obj     = value.toObject();
            url          = obj["name"].toString();
        }

【问题讨论】:

    标签: c++ json qt qt5 qtcore


    【解决方案1】:

    这是罪魁祸首:

    QJsonArray jsonArray = jsonObject["user"].toArray();
    

    您正在尝试将对象转换为数组而没有任何isArray() 检查。也就是说,您的 json 中不包含数组。数组在json世界中表示[...]

    您应该使用 toObject() 或更改您的输入 json。

    如果不改变 json 文件,你会这样写:

    QJsonDocument jsonResponse = QJsonDocument::fromJson(result.toUtf8());
    QJsonObject jsonObject = jsonResponse.object();
    QJsonObject userJsonObject = jsonObject.value("user").toObject();
    qDebug() << userJsonObject.value("name").toString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多