Skip to content
Permalink
Browse files
Add method to convert json to QVariant an capture errors in a string
  • Loading branch information
nyalldawson committed Dec 20, 2021
1 parent 568f527 commit 2406286a0b3277abbc90999abc1582dcf4d5ad4c
Showing with 28 additions and 3 deletions.
  1. +16 −2 src/core/qgsjsonutils.cpp
  2. +12 −1 src/core/qgsjsonutils.h
@@ -454,6 +454,19 @@ json QgsJsonUtils::jsonFromVariant( const QVariant &val )
}

QVariant QgsJsonUtils::parseJson( const std::string &jsonString )
{
QString error;
const QVariant res = parseJson( jsonString, error );

if ( !error.isEmpty() )
{
QgsLogger::warning( QStringLiteral( "Cannot parse json (%1): %2" ).arg( error,
QString::fromStdString( jsonString ) ) );
}
return res;
}

QVariant QgsJsonUtils::parseJson( const std::string &jsonString, QString &error )
{
// tracks whether entire json string is a primitive
bool isPrimitive = true;
@@ -464,6 +477,7 @@ QVariant QgsJsonUtils::parseJson( const std::string &jsonString )
{
isPrimitive = false;
QVariantList results;
results.reserve( jObj.size() );
for ( const auto &item : jObj )
{
results.push_back( _parser( item ) );
@@ -521,15 +535,15 @@ QVariant QgsJsonUtils::parseJson( const std::string &jsonString )
}
};

error.clear();
try
{
const json j = json::parse( jsonString );
return _parser( j );
}
catch ( json::parse_error &ex )
{
QgsLogger::warning( QStringLiteral( "Cannot parse json (%1): %2" ).arg( QString::fromStdString( ex.what() ),
QString::fromStdString( jsonString ) ) );
error = QString::fromStdString( ex.what() );
}
return QVariant();
}
@@ -359,12 +359,23 @@ class CORE_EXPORT QgsJsonUtils
static json jsonFromVariant( const QVariant &v ) SIP_SKIP;

/**
* Converts JSON \a jsonString to a QVariant, in case of parsing error an invalid QVariant is returned.
* Converts JSON \a jsonString to a QVariant, in case of parsing error an invalid QVariant is returned and an
* error is logged to the message log.
*
* \note Not available in Python bindings
* \since QGIS 3.8
*/
static QVariant parseJson( const std::string &jsonString ) SIP_SKIP;

/**
* Converts JSON \a jsonString to a QVariant, in case of parsing error an invalid QVariant is returned
* and the \a error argument is populated accordingly.
*
* \note Not available in Python bindings
* \since QGIS 3.24
*/
static QVariant parseJson( const std::string &jsonString, QString &error ) SIP_SKIP;

/**
* Converts JSON \a jsonString to a QVariant, in case of parsing error an invalid QVariant is returned.
* \note Not available in Python bindings

0 comments on commit 2406286

Please sign in to comment.