Qt解析json响应

时间:2013-07-24 12:58:32

标签: c++ json qt parsing

我需要解析一个看起来像这样的json响应并获取id值,即blabla2:

{
 "kind": "blabla",
 "id": "blabla2",
 "longUrl": "blabla3"
}

我该怎么做?我尝试使用Qjson,但是当我尝试使用Qjson来获取.dll时,我收到错误:

  

缺少xlocale.h。

enter image description here

还有其他选择吗?感谢。

2 个答案:

答案 0 :(得分:9)

查看QJsonDocument的文档,您可以将文件读入QByteArray,然后执行以下操作: -

// assuming a QByteArray contains the json file data

QJsonParseError err;
QJsonDocument doc = QJsonDocument::fromJson(byteArray, &err);

// test for error...

然后使用QJsonDocument上的函数来检索顶级对象...

if(doc.isObject())
{
    QJsonObject obj = doc.object();
    QJsonObject::iterator itr = obj.find("id");
    if(itr == obj.end())
    {
        // object not found.
    }

    // do something with the found object...

}

QJsonObject中还有一个value()函数,所以你可以简单地调用: -

而不是使用迭代器并调用find。
QJsonValue val = obj.value("id");

免责声明:我刚刚阅读了Qt文档后提供此代码,因此不要只复制并粘贴它,而应将其视为伪代码。您可能需要对其进行一些编辑,但希望有所帮助。

答案 1 :(得分:3)

我鼓励你使用Qt 5或将json类反向移植到Qt 4.当你打算将它移植到Qt 5时,你的软件会更加面向未来,因为你需要重写json解析然后在QtCore中可用

我会写下面的代码,但请在生产中使用它之前仔细检查它,因为我可能在编写时错过了错误检查。无论错误检查如何,输出都是您想要的。

的main.cpp

#include <QFile>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

int main()
{
    QFile file("main.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Could not open the file" << file.fileName() << "for reading:" << file.errorString();
        return 1;
    }

    QByteArray jsonData = file.readAll();
    if (file.error() != QFile::NoError) {
        qDebug() << QString("Failed to read from file %1, error: %2").arg(file.fileName()).arg(file.errorString());
        return 2;
    }

    if (jsonData.isEmpty()) {
        qDebug() << "No data was currently available for reading from file" << file.fileName();
        return 3;
    }

    QJsonDocument document = QJsonDocument::fromJson(jsonData);
    if (!document.isObject()) {
        qDebug() << "Document is not an object";
        return 4;
    }
    QJsonObject object = document.object();
    QJsonValue jsonValue = object.value("id");
    if (jsonValue.isUndefined()) {
        qDebug() << "Key id does not exist";
        return 5;
    }
    if (!jsonValue.isString()) {
        qDebug() << "Value not string";
        return 6;
    }

    qDebug() << jsonValue.toString();
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

构建并运行

qmake && make && ./main

输出

"blabla2"