From cc0080b00aac8b8c21b62ca260534f47badd1fa3 Mon Sep 17 00:00:00 2001 From: DonLakeFlyer Date: Wed, 1 Jul 2020 15:44:34 -0700 Subject: [PATCH] Add new isJsonFile method with input of QFile --- src/JsonHelper.cc | 16 ++++++++++++++++ src/JsonHelper.h | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/src/JsonHelper.cc b/src/JsonHelper.cc index a1fcd9771..da9d37463 100644 --- a/src/JsonHelper.cc +++ b/src/JsonHelper.cc @@ -225,11 +225,27 @@ bool JsonHelper::isJsonFile(const QByteArray& bytes, QJsonDocument& jsonDoc, QSt if (parseError.error == QJsonParseError::NoError) { return true; } else { + int startPos = qMax(0, parseError.offset - 100); + int length = qMin(bytes.count() - startPos, 200); + qDebug() << QStringLiteral("Json read error '%1'").arg(bytes.mid(startPos, length).constData()); errorString = parseError.errorString(); return false; } } +bool JsonHelper::isJsonFile(const QString& fileName, QJsonDocument& jsonDoc, QString& errorString) +{ + QFile jsonFile(fileName); + if (!jsonFile.open(QFile::ReadOnly)) { + errorString = tr("File open failed: file:error %1 %2").arg(jsonFile.fileName()).arg(jsonFile.errorString()); + return false; + } + QByteArray jsonBytes = jsonFile.readAll(); + jsonFile.close(); + + return isJsonFile(jsonBytes, jsonDoc, errorString); +} + bool JsonHelper::validateInternalQGCJsonFile(const QJsonObject& jsonObject, const QString& expectedFileType, int minSupportedVersion, diff --git a/src/JsonHelper.h b/src/JsonHelper.h index d4fb3f233..66d2026d7 100644 --- a/src/JsonHelper.h +++ b/src/JsonHelper.h @@ -26,6 +26,12 @@ class JsonHelper Q_DECLARE_TR_FUNCTIONS(JsonHelper) public: + /// Determines is the specified file is a json file + /// @return true: file is json, false: file is not json + static bool isJsonFile(const QString& fileName, ///< filename + QJsonDocument& jsonDoc, ///< returned json document + QString& errorString); ///< error on parse failure + /// Determines is the specified data is a json file /// @return true: file is json, false: file is not json static bool isJsonFile(const QByteArray& bytes, ///< json bytes -- 2.22.0