2

我有一个 json 对象,如何获取对象名称?我不能有对象名称,它将由服务器发送,这样我应该得到对象名称。

{
    "success":1,
    "return":{
        "343152":{//get this object name
            "pair":"usd_eur",
            "type":"sell",
            "amount":1.00000000,
            "rate":3.00000000,
            "timestamp_created":1342448420,
            "status":0
        }
                "343157":{//get this object name
            "pair":"usd_eur",
            "type":"sell",
            "amount":1.00000000,
            "rate":3.00000000,
            "timestamp_created":1342448420,
            "status":0
        }
    }

}
4

2 回答 2

4

您应该在版本 >= 5.X 的 QtCore 中使用 json 支持。您可以使用以下代码执行此操作:

json.txt

{
    "success": 1,
    "return": {
        "343152": {
            "pair": "usd_eur",
            "type": "sell",
            "amount": 1.00000000,
            "rate": 3.00000000,
            "timestamp_created": 1342448420,
            "status": 0
        },

        "343157": {
            "pair": "usd_eur",
            "type": "sell",
            "amount ":1.00000000,
            "rate": 3.00000000,
            "timestamp_created": 1342448420,
            "status": 0
        }
    }
}

主文件

#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>

#include <QByteArray>
#include <QStringList>
#include <QDebug>
#include <QFile>

int main()
{
    QFile file("json.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "File open error:" << file.errorString();
        return 1;
    }

    QByteArray jsonByteArray = file.readAll();

    file.close();

    QJsonParseError jsonParseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonByteArray, &jsonParseError);
    if (jsonParseError.error != QJsonParseError::NoError) {
        qDebug() << "Error happened:" << jsonParseError.errorString();
        return 1;
    }

    if (!jsonDocument.isObject()) {
        qDebug() << "The json data is not an object";
        return 1;
    }

    QJsonObject mainJsonObject(jsonDocument.object());

    QJsonValue returnJsonValue = mainJsonObject.value(QStringLiteral("return"));

    if (!returnJsonValue.isObject()) {
        qDebug() << "The json data is not an object";
        return 1;
    }

    qDebug() << "KEYS WANTED:" << returnJsonValue.toObject().keys();

    return 0;
}

输出

g++ -Wall -fPIC -I/usr/include/qt -I/usr/include/qt/QtCore -I/usr/include -lQt5Core main.cpp && ./a.out

KEYS WANTED: ("343152", "343157")
于 2013-12-22T15:59:04.820 回答
1

由于您的帖子被标记为 qjson,我假设您正在使用它...

QJson::Parser parser;
bool ok;
QVariantMap result = parser.parse (json, &ok).toMap(); // json is a QByteArray w. the data
QVariantMap returnMap = result["return"].toMap();

// iterate your map to get the names you're interested in.
for(QVariantMap::const_iterator iter = returnMap.begin(); iter != returnMap.end(); ++iter) {
    qDebug() << iter.key();
}

// Do whatever you need with yourObj..

http://qjson.sourceforge.net/usage/

于 2013-12-22T15:45:24.743 回答