Skip to content
Snippets Groups Projects
json.cpp 1.22 KiB
Newer Older
akiraohgaki's avatar
akiraohgaki committed
/**
 * A library for Qt app
 *
 * LICENSE: The GNU Lesser General Public License, version 3.0
 *
 * @author      Akira Ohgaki <akiraohgaki@gmail.com>
 * @copyright   Akira Ohgaki
 * @license     https://opensource.org/licenses/LGPL-3.0  The GNU Lesser General Public License, version 3.0
 * @link        https://github.com/akiraohgaki/qt-libs
 */

akiraohgaki's avatar
akiraohgaki committed
#include "json.h"

akiraohgaki's avatar
akiraohgaki committed
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

akiraohgaki's avatar
akiraohgaki committed
namespace utils {
akiraohgaki's avatar
akiraohgaki committed

Json::Json(QObject *parent) : QObject(parent)
{}

akiraohgaki's avatar
akiraohgaki committed
QString Json::convertObjToStr(const QJsonObject &jsonObj)
akiraohgaki's avatar
akiraohgaki committed
{
akiraohgaki's avatar
akiraohgaki committed
    QJsonDocument jsonDoc(jsonObj);
    return QString::fromUtf8(jsonDoc.toJson());
akiraohgaki's avatar
akiraohgaki committed
}

QJsonObject Json::convertStrToObj(const QString &json)
{
    QJsonObject jsonObj;
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(json.toUtf8(), &jsonError);
    if (jsonError.error == QJsonParseError::NoError && jsonDoc.isObject()) {
        jsonObj = jsonDoc.object();
    }
    return jsonObj;
}

akiraohgaki's avatar
akiraohgaki committed
bool Json::isValid(const QString &json)
akiraohgaki's avatar
akiraohgaki committed
{
akiraohgaki's avatar
akiraohgaki committed
    QJsonParseError jsonError;
    QJsonDocument::fromJson(json.toUtf8(), &jsonError);
    if (jsonError.error == QJsonParseError::NoError) {
        return true;
    }
    return false;
akiraohgaki's avatar
akiraohgaki committed
} // namespace utils