36#include <QJsonDocument>
39#include <nlohmann/json.hpp>
43 , mLayer( vectorLayer )
83 const QVariant &
id,
int indent )
const
92 {
"type",
"Feature" },
97 auto intId =
id.toLongLong( &ok );
100 featureJson[
"id"] = intId;
104 featureJson[
"id"] =
id.toString().toStdString();
109 featureJson[
"id"] =
nullptr;
113 featureJson[
"id"] = feature.
id();
117 if ( !geom.
isNull() && mIncludeGeometry )
136 featureJson[
"bbox" ] =
144 featureJson[
"geometry" ] = geom.
asJsonObject( mPrecision );
148 featureJson[
"geometry" ] =
nullptr;
153 if ( mIncludeAttributes || !extraProperties.isEmpty() )
156 if ( mIncludeAttributes )
160 QStringList formattersAllowList;
161 formattersAllowList << QStringLiteral(
"KeyValue" )
162 << QStringLiteral(
"List" )
163 << QStringLiteral(
"ValueRelation" )
164 << QStringLiteral(
"ValueMap" );
166 for (
int i = 0; i < fields.
count(); ++i )
168 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
173 if ( mUseFieldFormatters && mLayer )
177 if ( formattersAllowList.contains( fieldFormatter->
id() ) )
181 QString name = fields.
at( i ).
name();
182 if ( mAttributeDisplayName )
184 name = mLayer->attributeDisplayName( i );
190 if ( !extraProperties.isEmpty() )
192 QVariantMap::const_iterator it = extraProperties.constBegin();
193 for ( ; it != extraProperties.constEnd(); ++it )
200 if ( mLayer && mIncludeRelatedAttributes )
203 for (
const auto &relation : std::as_const( relations ) )
208 json relatedFeatureAttributes;
212 QVector<QVariant> attributeWidgetCaches;
215 for (
const QgsField &field : fields )
219 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
228 properties[ relation.name().toStdString() ] = relatedFeatureAttributes;
232 featureJson[
"properties" ] = properties;
245 {
"type",
"FeatureCollection" },
246 {
"features", json::array() }
251 for (
const QgsFeature &feature : std::as_const( features ) )
260 mDestinationCrs = destinationCrs;
271 encoding = QTextCodec::codecForName(
"UTF-8" );
279 encoding = QTextCodec::codecForName(
"UTF-8" );
287 return QStringLiteral(
"null" );
289 switch ( value.userType() )
291 case QMetaType::Type::Int:
292 case QMetaType::Type::UInt:
293 case QMetaType::Type::LongLong:
294 case QMetaType::Type::ULongLong:
295 case QMetaType::Type::Double:
296 return value.toString();
298 case QMetaType::Type::Bool:
299 return value.toBool() ?
"true" :
"false";
301 case QMetaType::Type::QStringList:
302 case QMetaType::Type::QVariantList:
303 case QMetaType::Type::QVariantMap:
304 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
307 case QMetaType::Type::QString:
308 QString v = value.toString()
309 .replace(
'\\', QLatin1String(
"\\\\" ) )
310 .replace(
'"', QLatin1String(
"\\\"" ) )
311 .replace(
'\r', QLatin1String(
"\\r" ) )
312 .replace(
'\b', QLatin1String(
"\\b" ) )
313 .replace(
'\t', QLatin1String(
"\\t" ) )
314 .replace(
'/', QLatin1String(
"\\/" ) )
315 .replace(
'\n', QLatin1String(
"\\n" ) );
317 return v.prepend(
'"' ).append(
'"' );
325 for (
int i = 0; i < fields.
count(); ++i )
328 attrs += QLatin1String(
",\n" );
337 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
342 return attrs.prepend(
'{' ).append(
'}' );
347 QString errorMessage;
351 const auto jObj( json::parse( json.toStdString() ) );
352 if ( ! jObj.is_array() )
354 throw json::parse_error::create( 0, 0, QStringLiteral(
"JSON value must be an array" ).toStdString() );
356 for (
const auto &item : jObj )
360 if ( item.is_number_integer() )
364 else if ( item.is_number_unsigned() )
366 v = item.get<
unsigned>();
368 else if ( item.is_number_float() )
371 v = item.get<
double>();
373 else if ( item.is_string() )
375 v = QString::fromStdString( item.get<std::string>() );
377 else if ( item.is_boolean() )
379 v = item.get<
bool>();
381 else if ( item.is_null() )
388 if ( type != QMetaType::Type::UnknownType )
390 if ( ! v.convert(
static_cast<int>( type ) ) )
392 QgsLogger::warning( QStringLiteral(
"Cannot convert json array element to specified type, ignoring: %1" ).arg( v.toString() ) );
396 result.push_back( v );
401 result.push_back( v );
405 catch ( json::parse_error &ex )
407 errorMessage = ex.what();
408 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( ex.what(), json ) );
421 if ( !coords.is_array() || coords.size() < 2 || coords.size() > 3 )
423 QgsDebugError( QStringLiteral(
"JSON Point geometry coordinates must be an array of two or three numbers" ) );
427 const double x = coords[0].get<
double >();
428 const double y = coords[1].get<
double >();
429 if ( coords.size() == 2 )
431 return std::make_unique< QgsPoint >( x, y );
435 const double z = coords[2].get<
double >();
436 return std::make_unique< QgsPoint >( x, y, z );
442 if ( !coords.is_array() || coords.size() < 2 )
444 QgsDebugError( QStringLiteral(
"JSON LineString geometry coordinates must be an array of at least two points" ) );
448 const std::size_t coordsSize = coords.size();
453#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
454 x.resize(
static_cast< int >( coordsSize ) );
455 y.resize(
static_cast< int >( coordsSize ) );
456 z.resize(
static_cast< int >( coordsSize ) );
458 x.resize( coordsSize );
459 y.resize( coordsSize );
460 z.resize( coordsSize );
462 double *xOut = x.data();
463 double *yOut = y.data();
464 double *zOut = z.data();
466 for (
const auto &coord : coords )
468 if ( !coord.is_array() || coord.size() < 2 || coord.size() > 3 )
470 QgsDebugError( QStringLiteral(
"JSON LineString geometry coordinates must be an array of two or three numbers" ) );
474 *xOut++ = coord[0].get<
double >();
475 *yOut++ = coord[1].get<
double >();
476 if ( coord.size() == 3 )
478 *zOut++ = coord[2].get<
double >();
483 *zOut++ = std::numeric_limits< double >::quiet_NaN();
487 return std::make_unique< QgsLineString >( x, y, hasZ ? z : QVector<double>() );
492 if ( !coords.is_array() || coords.size() < 1 )
494 QgsDebugError( QStringLiteral(
"JSON Polygon geometry coordinates must be an array" ) );
498 const std::size_t coordsSize = coords.size();
505 std::unique_ptr< QgsPolygon > polygon = std::make_unique< QgsPolygon >( exterior.release() );
506 for ( std::size_t i = 1; i < coordsSize; ++i )
513 polygon->addInteriorRing( ring.release() );
520 if ( !geometry.is_object() )
522 QgsDebugError( QStringLiteral(
"JSON geometry value must be an object" ) );
526 if ( !geometry.contains(
"type" ) )
528 QgsDebugError( QStringLiteral(
"JSON geometry must contain 'type'" ) );
532 const QString type = QString::fromStdString( geometry[
"type"].get< std::string >() );
533 if ( type.compare( QLatin1String(
"Point" ), Qt::CaseInsensitive ) == 0 )
535 if ( !geometry.contains(
"coordinates" ) )
537 QgsDebugError( QStringLiteral(
"JSON Point geometry must contain 'coordinates'" ) );
541 const json &coords = geometry[
"coordinates"];
544 else if ( type.compare( QLatin1String(
"MultiPoint" ), Qt::CaseInsensitive ) == 0 )
546 if ( !geometry.contains(
"coordinates" ) )
548 QgsDebugError( QStringLiteral(
"JSON MultiPoint geometry must contain 'coordinates'" ) );
552 const json &coords = geometry[
"coordinates"];
554 if ( !coords.is_array() )
556 QgsDebugError( QStringLiteral(
"JSON MultiPoint geometry coordinates must be an array" ) );
560 std::unique_ptr< QgsMultiPoint > multiPoint = std::make_unique< QgsMultiPoint >();
561 multiPoint->reserve(
static_cast< int >( coords.size() ) );
562 for (
const auto &pointCoords : coords )
569 multiPoint->addGeometry( point.release() );
574 else if ( type.compare( QLatin1String(
"LineString" ), Qt::CaseInsensitive ) == 0 )
576 if ( !geometry.contains(
"coordinates" ) )
578 QgsDebugError( QStringLiteral(
"JSON LineString geometry must contain 'coordinates'" ) );
582 const json &coords = geometry[
"coordinates"];
585 else if ( type.compare( QLatin1String(
"MultiLineString" ), Qt::CaseInsensitive ) == 0 )
587 if ( !geometry.contains(
"coordinates" ) )
589 QgsDebugError( QStringLiteral(
"JSON MultiLineString geometry must contain 'coordinates'" ) );
593 const json &coords = geometry[
"coordinates"];
595 if ( !coords.is_array() )
597 QgsDebugError( QStringLiteral(
"JSON MultiLineString geometry coordinates must be an array" ) );
601 std::unique_ptr< QgsMultiLineString > multiLineString = std::make_unique< QgsMultiLineString >();
602 multiLineString->reserve(
static_cast< int >( coords.size() ) );
603 for (
const auto &lineCoords : coords )
610 multiLineString->addGeometry( line.release() );
613 return multiLineString;
615 else if ( type.compare( QLatin1String(
"Polygon" ), Qt::CaseInsensitive ) == 0 )
617 if ( !geometry.contains(
"coordinates" ) )
619 QgsDebugError( QStringLiteral(
"JSON Polygon geometry must contain 'coordinates'" ) );
623 const json &coords = geometry[
"coordinates"];
624 if ( !coords.is_array() || coords.size() < 1 )
626 QgsDebugError( QStringLiteral(
"JSON Polygon geometry coordinates must be an array of at least one ring" ) );
632 else if ( type.compare( QLatin1String(
"MultiPolygon" ), Qt::CaseInsensitive ) == 0 )
634 if ( !geometry.contains(
"coordinates" ) )
636 QgsDebugError( QStringLiteral(
"JSON MultiPolygon geometry must contain 'coordinates'" ) );
640 const json &coords = geometry[
"coordinates"];
642 if ( !coords.is_array() )
644 QgsDebugError( QStringLiteral(
"JSON MultiPolygon geometry coordinates must be an array" ) );
648 std::unique_ptr< QgsMultiPolygon > multiPolygon = std::make_unique< QgsMultiPolygon >();
649 multiPolygon->reserve(
static_cast< int >( coords.size() ) );
650 for (
const auto &polygonCoords : coords )
657 multiPolygon->addGeometry( polygon.release() );
662 else if ( type.compare( QLatin1String(
"GeometryCollection" ), Qt::CaseInsensitive ) == 0 )
664 if ( !geometry.contains(
"geometries" ) )
666 QgsDebugError( QStringLiteral(
"JSON GeometryCollection geometry must contain 'geometries'" ) );
670 const json &geometries = geometry[
"geometries"];
672 if ( !geometries.is_array() )
674 QgsDebugError( QStringLiteral(
"JSON GeometryCollection geometries must be an array" ) );
678 std::unique_ptr< QgsGeometryCollection > collection = std::make_unique< QgsGeometryCollection >();
679 collection->reserve(
static_cast< int >( geometries.size() ) );
680 for (
const auto &geometry : geometries )
687 collection->addGeometry(
object.release() );
693 QgsDebugError( QStringLiteral(
"Unhandled GeoJSON geometry type: %1" ).arg( type ) );
699 if ( !geometry.is_object() )
701 QgsDebugError( QStringLiteral(
"JSON geometry value must be an object" ) );
712 const auto jObj( json::parse( geometry.toStdString() ) );
715 catch ( json::parse_error &ex )
717 QgsDebugError( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( geometry, ex.what() ) );
729 if ( val.userType() == QMetaType::Type::QVariantMap )
731 const QVariantMap &vMap = val.toMap();
732 json jMap = json::object();
733 for (
auto it = vMap.constBegin(); it != vMap.constEnd(); it++ )
739 else if ( val.userType() == QMetaType::Type::QVariantList || val.userType() == QMetaType::Type::QStringList )
741 const QVariantList &vList = val.toList();
742 json jList = json::array();
743 for (
const auto &v : vList )
751 switch ( val.userType() )
754 case QMetaType::UInt:
755 case QMetaType::LongLong:
756 case QMetaType::ULongLong:
757 j = val.toLongLong();
759 case QMetaType::Double:
760 case QMetaType::Float:
763 case QMetaType::Bool:
766 case QMetaType::QByteArray:
767 j = val.toByteArray().toBase64().toStdString();
770 j = val.toString().toStdString();
780 const QVariant res =
parseJson( jsonString, error );
782 if ( !error.isEmpty() )
785 QString::fromStdString( jsonString ) ) );
795 const json j = json::parse( jsonString );
798 catch ( json::parse_error &ex )
800 error = QString::fromStdString( ex.what() );
808 bool isPrimitive =
true;
810 std::function<QVariant( json )> _parser { [ & ]( json jObj ) -> QVariant {
812 if ( jObj.is_array() )
815 QVariantList results;
816 results.reserve( jObj.size() );
817 for (
const auto &item : jObj )
819 results.push_back( _parser( item ) );
823 else if ( jObj.is_object() )
827 for (
const auto &item : jObj.items() )
829 const auto key { QString::fromStdString( item.key() ) };
830 const auto value { _parser( item.value() ) };
831 results[ key ] = value;
837 if ( jObj.is_number_unsigned() )
841 const qulonglong num { jObj.get<qulonglong>() };
842 if ( num <= std::numeric_limits<int>::max() )
844 result =
static_cast<int>( num );
846 else if ( num <= std::numeric_limits<qlonglong>::max() )
848 result =
static_cast<qlonglong
>( num );
855 else if ( jObj.is_number_integer() )
857 const qlonglong num { jObj.get<qlonglong>() };
858 if ( num <= std::numeric_limits<int>::max() && num >= std::numeric_limits<int>::lowest() )
860 result =
static_cast<int>( num );
867 else if ( jObj.is_boolean() )
869 result = jObj.get<
bool>();
871 else if ( jObj.is_number_float() )
874 result = jObj.get<
double>();
876 else if ( jObj.is_string() )
878 if ( isPrimitive && jObj.get<std::string>().length() == 0 )
880 result = QString::fromStdString( jObj.get<std::string>() ).append(
"\"" ).insert( 0,
"\"" );
884 result = QString::fromStdString( jObj.get<std::string>() );
887 else if ( jObj.is_null() )
896 return _parser( value );
901 return parseJson( jsonString.toStdString() );
908 for (
int i = 0; i < fields.
count(); ++i )
912 if ( layer && useFieldFormatters )
917 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
931 value[
"crs"][
"type"] =
"name";
932 value[
"crs"][
"properties"][
"name"] =
crs.
toOgcUrn().toStdString();
@ Success
Operation succeeded.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QString toOgcUrn() const
Returns the crs as OGC URN (format: urn:ogc:def:crs:OGC:1.3:CRS84) Returns an empty string on failure...
Custom exception class for Coordinate Reference System related exceptions.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Encapsulate a field in an attribute table or data source.
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
Container of fields for a vector layer.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
virtual json asJsonObject(int precision=17) const
Exports the geometry to a json object.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
json exportFeatureToJsonObject(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant()) const
Returns a QJsonObject representation of a feature.
json exportFeaturesToJsonObject(const QgsFeatureList &features) const
Returns a JSON object representation of a list of features (feature collection).
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source CRS for feature geometries.
void setDestinationCrs(const QgsCoordinateReferenceSystem &destinationCrs)
Set the destination CRS for feature geometry transformation to destinationCrs, this defaults to EPSG:...
QgsVectorLayer * vectorLayer() const
Returns the associated vector layer, if set.
QString exportFeature(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant(), int indent=-1) const
Returns a GeoJSON string representation of a feature.
QString exportFeatures(const QgsFeatureList &features, int indent=-1) const
Returns a GeoJSON string representation of a list of features (feature collection).
void setVectorLayer(QgsVectorLayer *vectorLayer)
Sets the associated vector layer (required for related attribute export).
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source CRS for feature geometries.
QgsJsonExporter(QgsVectorLayer *vectorLayer=nullptr, int precision=6)
Constructor for QgsJsonExporter.
static QgsGeometry geometryFromGeoJson(const json &geometry)
Parses a GeoJSON "geometry" value to a QgsGeometry object.
static QString exportAttributes(const QgsFeature &feature, QgsVectorLayer *layer=nullptr, const QVector< QVariant > &attributeWidgetCaches=QVector< QVariant >())
Exports all attributes from a QgsFeature as a JSON map type.
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields=QgsFields(), QTextCodec *encoding SIP_PYARGREMOVE6=nullptr)
Attempts to parse a GeoJSON string to a collection of features.
static Q_INVOKABLE QString encodeValue(const QVariant &value)
Encodes a value to a JSON string representation, adding appropriate quotations and escaping where req...
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned and ...
static void addCrsInfo(json &value, const QgsCoordinateReferenceSystem &crs)
Add crs information entry in json object regarding old GeoJSON specification format if it differs fro...
static Q_INVOKABLE QVariantList parseArray(const QString &json, QMetaType::Type type=QMetaType::Type::UnknownType)
Parse a simple array (depth=1)
static json exportAttributesToJsonObject(const QgsFeature &feature, QgsVectorLayer *layer=nullptr, const QVector< QVariant > &attributeWidgetCaches=QVector< QVariant >(), bool useFieldFormatters=true)
Exports all attributes from a QgsFeature as a json object.
static QVariant jsonToVariant(const json &value)
Converts a JSON value to a QVariant, in case of parsing error an invalid QVariant is returned.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding SIP_PYARGREMOVE6=nullptr)
Attempts to retrieve the fields from a GeoJSON string representing a collection of features.
static json jsonFromVariant(const QVariant &v)
Converts a QVariant v to a json object.
static void warning(const QString &msg)
Goes to qWarning.
QgsCoordinateReferenceSystem crs
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a string representing a collection of features using OGR.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a string representing a collection of features using OGR.
QgsRelationManager * relationManager
static QgsProject * instance()
Returns the QgsProject singleton instance.
A rectangle specified with double values.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double xMaximum() const
Returns the x maximum value (right side of rectangle).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
QList< QgsRelation > referencedRelations(const QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
static QMetaType::Type variantTypeToMetaType(QVariant::Type variantType)
Converts a QVariant::Type to a QMetaType::Type.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
static QVariant createNullVariant(QMetaType::Type metaType)
Helper method to properly create a null QVariant from a metaType Returns the created QVariant.
Represents a vector layer which manages a vector based data sets.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
double qgsRound(double number, int places)
Returns a double number, rounded (as close as possible) to the specified number of places.
QList< QgsFeature > QgsFeatureList
std::unique_ptr< QgsPoint > parsePointFromGeoJson(const json &coords)
std::unique_ptr< QgsPolygon > parsePolygonFromGeoJson(const json &coords)
std::unique_ptr< QgsAbstractGeometry > parseGeometryFromGeoJson(const json &geometry)
std::unique_ptr< QgsLineString > parseLineStringFromGeoJson(const json &coords)
#define QgsDebugError(str)
const QgsCoordinateReferenceSystem & crs