将JSON文本文件转换回QJsonArray

问题描述 投票:0回答:1

我有一个对象,我使用下面的代码将它序列化为JSON(也参见结构):

struct RegisterItem {
    RegisterType Type = RegisterType::ReadWrite;
    QString Name = QStringLiteral("REGISTER");
    int Bank = 0; 
    int Address = 0;
    int Range = 1;
    int DefaultValue = 0;
    int CurrentValue = 0;
    int SpecialAction = REG_SPECIAL_ACTION_NONE;
};

此代码将其转换为json文本文件:

bool saveRegisterStateToFile(const QVector<RegisterWidget*>& widgets)
{
    QJsonArray arr;

    for(int i = 0; i < widgets.size(); i++) {

        RegisterItem item = widgets[i]->registerItem();
        auto data = QJsonObject({

                                    qMakePair(QString("Address"), QJsonValue(item.Address)),
                                    qMakePair(QString("Name"), QJsonValue(item.Name)),
                                    qMakePair(QString("Bank"), QJsonValue(item.Bank)),
                                    qMakePair(QString("Type"), QJsonValue(static_cast<int>(item.Type))),
                                    qMakePair(QString("DefaultValue"), QJsonValue(item.DefaultValue)),
                                    qMakePair(QString("SpecialAction"), QJsonValue(item.SpecialAction))
                                });
        arr.push_back(data);
    }

    QFile file("json.txt");
    file.open(QFile::WriteOnly);
    file.write(QJsonDocument(arr).toJson());
}

这一切都很好,并生成json文件......它看起来像这样(前几行):

[
    {
        "Address": 0,
        "Bank": 0,
        "DefaultValue": 0,
        "Name": "V_ADC_IN",
        "SpecialAction": 0,
        "Type": 3
    },
    {
        "Address": 1,
        "Bank": 0,
        "DefaultValue": 0,
        "Name": "V_ADC_SCALE",
        "SpecialAction": 0,
        "Type": 3
    },
    {
        "Address": 2,
        "Bank": 0,

现在,我需要反向...但我的json对象大小始终为0!问题是什么?

QFile file(url);

file.open(QIODevice::ReadOnly | QIODevice::Text);
QString raw = file.readAll();
file.close();

QJsonDocument doc = QJsonDocument::fromJson(raw.toUtf8());
QJsonObject obj = doc.object();
QJsonArray arr = obj[""].toArray();
c++ qt qjson qjsonobject
1个回答
1
投票

您的对象没有标识符...因此您需要按阵列中的位置进行访问。像这样的东西:

QJsonDocument doc = QJsonDocument::fromJson(raw.toUtf8());
QJsonArray arr = doc.array(); // get array representation of the doc

for(int i = 0; i < arr.size(); i++) {
        QJsonValue val = arr.at(i);
        // The following line should thoritically prin the Name field
        qDebug() << val.toObject().value("Name");
}
© www.soinside.com 2019 - 2024. All rights reserved.