qt/LedOK/jsondecoderloop.cpp

51 lines
1.2 KiB
C++
Raw Normal View History

2022-01-04 18:11:48 +08:00
#include "jsondecoderloop.h"
#include <iostream>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QStringList>
JsonDecoderLoop::JsonDecoderLoop()
{
}
QString JsonDecoderLoop::decode(const QByteArray byteArray, QString key)
{
// Check input
if ( byteArray.isEmpty() || 0 == key.compare(""))
{
return "";
}
QString str = "";
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray, &jsonError);
if(jsonError.error == QJsonParseError::NoError)
{
if(jsonDoc.isObject())
{
QJsonObject obj = jsonDoc.object();
// Loop get value according the key world
str = getValueBykey(obj, key);
}
}
return str;
}
QString JsonDecoderLoop::getValueBykey(QJsonObject obj, QString key)
{
QString rst = "";
QStringList strList = obj.keys();
for (int i = 0; i < obj.size(); i++)
{
QJsonValue val = obj.value(strList.at(i));
if ( strList.at(i) == key && val.isString())
{
rst = val.toString();
}
else if (val.isObject())
{
rst = getValueBykey(val.toObject(), key);
}
}
return rst;
}