Qt解析json响应

dda*_*cot 6 c++ qt parsing json

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

{
 "kind": "blabla",
 "id": "blabla2",
 "longUrl": "blabla3"
}
Run Code Online (Sandbox Code Playgroud)

我怎么做?我试图使用Qjson,但是当我尝试使用它时.dll,我得到了一个错误:

缺少xlocale.h.

在此输入图像描述

还有其他选择吗?谢谢.

The*_*ght 9

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

// assuming a QByteArray contains the json file data

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

// test for error...
Run Code Online (Sandbox Code Playgroud)

然后使用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...

}
Run Code Online (Sandbox Code Playgroud)

QJsonObject中还有一个value()函数,因此您可以简单地调用: - 而不是使用迭代器并调用find.

QJsonValue val = obj.value("id");
Run Code Online (Sandbox Code Playgroud)

免责声明:我刚刚阅读了Qt文档后提供了这段代码,所以不要只复制并粘贴它,而应将其视为伪代码.您可能需要稍微编辑一下,但希望有所帮助.


lpa*_*app 3

我鼓励您使用 Qt 5 或将 json 类反向移植到 Qt 4。当您打算将其移植到 Qt 5 时,您的软件将更具前瞻性,因为您需要重写 QtCore 中可用的 json 解析。

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

主程序

#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;
}
Run Code Online (Sandbox Code Playgroud)

主程序

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
Run Code Online (Sandbox Code Playgroud)

构建并运行

qmake && make && ./main
Run Code Online (Sandbox Code Playgroud)

输出

"blabla2"
Run Code Online (Sandbox Code Playgroud)