将 JSON 文本文件转换回 QJsonArray

Converting JSON text file back to QJsonArray

我有一个对象,我使用下面的代码将其序列化为 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();

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

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");
}