I am working with an API that delivers some data in a QStringList or basically a list of strings. The data contains keys and values but it is not a map or anything like that...just plain list.
The list has always an even number of elements where each pair are like key, value.
I need to efficiently create an object out of this list. I came up with a function that checks existence of a given key and returns it's associated value as a QVariant which then can easily convert to a given type. Here is my code:
#include <QCoreApplication>
#include <QVariant>
#include <QDebug>
struct MyData {
MyData() = default;
QString myString;
bool myBool;
int myInt;
float myFloat;
};
QVariant getValueByKey(const QStringList& list, const QString& key) {
auto keyIndex = list.indexOf(key);
qDebug() << "index of" << key << "is" << keyIndex;
if(keyIndex != -1 && list.size() > (keyIndex + 1)) {
return QVariant(list.at(keyIndex + 1));
}
return QVariant();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QStringList list { // Example list
"KEY-STRING", "String",
"KEY-BOOL", "true",
"KEY-INT", "2",
"KEY-FLOAT", "3.14"
};
MyData data;
data.myString = getValueByKey(list, "KEY-STRING").toString();
data.myBool = getValueByKey(list, "KEY-BOOL").toBool();
data.myInt = getValueByKey(list, "KEY-INT").toInt();
data.myFloat = getValueByKey(list, "KEY-FLOAT").toFloat();
qDebug() << "The string value is:\t" << data.myString.remove("\"");
qDebug() << "The bool value is:\t" << data.myBool;
qDebug() << "The int value is:\t" << data.myInt;
qDebug() << "The float value is:\t" << data.myFloat;
// Test arithmetic
qDebug() << "myInt * myFloat:\t" << data.myInt * data.myFloat;
qDebug() << "Testing invalid key: "
<< getValueByKey(list, "damn-son").toString();
return a.exec();
}
My Questions are:
- Does this code make sense?
- Is there a better way to do such task?
- My getValue function returns an empty QVariant, which is the same as an empty string. Is there a way to tell the caller of the function that something had gone wrong? is a pair of bool,qvariant senseful?