c++qtqjsonqjsonobject

Converting JSON text file back to QJsonArray


I have an object that I serialize it into JSON using the code below (also see the the struct):

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

This code converts it to json text file:

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

This all works fine and produces the json file...it looks like this (first few lines):

[
    {
        "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,

Now, I need to do the reverse...but my json object size is always 0! what is the problem?

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();

Solution

  • Your objects does not have an identifier...so you need to access by position in the array. Something like this:

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