18#include <nlohmann/json.hpp>
40#include <QJsonDocument>
44#include "moc_qgsjsonutils.cpp"
46using namespace Qt::StringLiterals;
55 mTransform.setSourceCrs( mCrs );
60 mTransform.setDestinationCrs( mDestinationCrs );
69 mTransform.setSourceCrs( mCrs );
81 mTransform.setSourceCrs( mCrs );
90 const QVariant &
id,
int indent )
const
96 catch ( json::type_error &ex )
101 catch ( json::other_error &ex )
112 {
"type",
"Feature" },
117 auto intId =
id.toLongLong( &ok );
120 featureJson[
"id"] = intId;
124 featureJson[
"id"] =
id.toString().toStdString();
129 featureJson[
"id"] =
nullptr;
133 featureJson[
"id"] = feature.
id();
137 if ( !geom.
isNull() && mIncludeGeometry )
139 if ( mCrs.isValid() )
156 featureJson[
"bbox" ] =
164 featureJson[
"geometry" ] = geom.
asJsonObject( mPrecision );
168 featureJson[
"geometry" ] =
nullptr;
173 if ( mIncludeAttributes || !extraProperties.isEmpty() )
176 if ( mIncludeAttributes )
180 QStringList formattersAllowList;
181 formattersAllowList << u
"KeyValue"_s
183 << u
"ValueRelation"_s
186 for (
int i = 0; i < fields.
count(); ++i )
188 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
193 if ( mUseFieldFormatters && mLayer )
197 if ( formattersAllowList.contains( fieldFormatter->
id() ) )
201 QString name = fields.
at( i ).
name();
202 if ( mAttributeDisplayName )
204 name = mLayer->attributeDisplayName( i );
210 if ( !extraProperties.isEmpty() )
212 QVariantMap::const_iterator it = extraProperties.constBegin();
213 for ( ; it != extraProperties.constEnd(); ++it )
220 if ( mLayer && mIncludeRelatedAttributes )
223 for (
const auto &relation : std::as_const( relations ) )
228 json relatedFeatureAttributes;
232 QVector<QVariant> attributeWidgetCaches;
235 for (
const QgsField &field : fields )
239 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
248 properties[ relation.name().toStdString() ] = relatedFeatureAttributes;
252 featureJson[
"properties" ] = properties;
265 {
"type",
"FeatureCollection" },
266 {
"features", json::array() }
271 for (
const QgsFeature &feature : std::as_const( features ) )
280 mDestinationCrs = destinationCrs;
281 mTransform.setDestinationCrs( mDestinationCrs );
291 encoding = QTextCodec::codecForName(
"UTF-8" );
299 encoding = QTextCodec::codecForName(
"UTF-8" );
309 switch ( value.userType() )
311 case QMetaType::Type::Int:
312 case QMetaType::Type::UInt:
313 case QMetaType::Type::LongLong:
314 case QMetaType::Type::ULongLong:
315 case QMetaType::Type::Double:
316 return value.toString();
318 case QMetaType::Type::Bool:
319 return value.toBool() ?
"true" :
"false";
321 case QMetaType::Type::QStringList:
322 case QMetaType::Type::QVariantList:
323 case QMetaType::Type::QVariantMap:
324 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
327 case QMetaType::Type::QString:
328 QString v = value.toString()
329 .replace(
'\\',
"\\\\"_L1 )
330 .replace(
'"',
"\\\""_L1 )
331 .replace(
'\r',
"\\r"_L1 )
332 .replace(
'\b',
"\\b"_L1 )
333 .replace(
'\t',
"\\t"_L1 )
334 .replace(
'/',
"\\/"_L1 )
335 .replace(
'\n',
"\\n"_L1 );
337 return v.prepend(
'"' ).append(
'"' );
345 for (
int i = 0; i < fields.
count(); ++i )
357 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
362 return attrs.prepend(
'{' ).
append(
'}' );
367 QString errorMessage;
371 const auto jObj( json::parse( json.toStdString() ) );
372 if ( ! jObj.is_array() )
374 throw json::parse_error::create( 0, 0, u
"JSON value must be an array"_s.toStdString(), &jObj );
376 for (
const auto &item : jObj )
380 if ( item.is_number_integer() )
384 else if ( item.is_number_unsigned() )
386 v = item.get<
unsigned>();
388 else if ( item.is_number_float() )
391 v = item.get<
double>();
393 else if ( item.is_string() )
395 v = QString::fromStdString( item.get<std::string>() );
397 else if ( item.is_boolean() )
399 v = item.get<
bool>();
401 else if ( item.is_null() )
408 if ( type != QMetaType::Type::UnknownType )
410 if ( ! v.convert(
static_cast<int>( type ) ) )
412 QgsLogger::warning( u
"Cannot convert json array element to specified type, ignoring: %1"_s.arg( v.toString() ) );
416 result.push_back( v );
421 result.push_back( v );
425 catch ( json::parse_error &ex )
427 errorMessage = ex.what();
441 if ( !coords.is_array() || coords.size() < 2 || coords.size() > 3 )
443 QgsDebugError( u
"JSON Point geometry coordinates must be an array of two or three numbers"_s );
447 const double x = coords[0].get<
double >();
448 const double y = coords[1].get<
double >();
449 if ( coords.size() == 2 )
451 return std::make_unique< QgsPoint >( x, y );
455 const double z = coords[2].get<
double >();
456 return std::make_unique< QgsPoint >( x, y, z );
462 if ( !coords.is_array() || coords.size() < 2 )
464 QgsDebugError( u
"JSON LineString geometry coordinates must be an array of at least two points"_s );
468 const std::size_t coordsSize = coords.size();
473 x.resize( coordsSize );
474 y.resize( coordsSize );
475 z.resize( coordsSize );
477 double *xOut = x.data();
478 double *yOut = y.data();
479 double *zOut = z.data();
481 for (
const auto &coord : coords )
483 if ( !coord.is_array() || coord.size() < 2 || coord.size() > 3 )
485 QgsDebugError( u
"JSON LineString geometry coordinates must be an array of two or three numbers"_s );
489 *xOut++ = coord[0].get<
double >();
490 *yOut++ = coord[1].get<
double >();
491 if ( coord.size() == 3 )
493 *zOut++ = coord[2].get<
double >();
498 *zOut++ = std::numeric_limits< double >::quiet_NaN();
502 return std::make_unique< QgsLineString >( x, y, hasZ ? z : QVector<double>() );
507 if ( !coords.is_array() || coords.size() < 1 )
509 QgsDebugError( u
"JSON Polygon geometry coordinates must be an array"_s );
513 const std::size_t coordsSize = coords.size();
520 auto polygon = std::make_unique< QgsPolygon >( exterior.release() );
521 for ( std::size_t i = 1; i < coordsSize; ++i )
528 polygon->addInteriorRing( ring.release() );
535 if ( !geometry.is_object() )
541 if ( !geometry.contains(
"type" ) )
547 const QString type = QString::fromStdString( geometry[
"type"].get< std::string >() );
548 if ( type.compare(
"Point"_L1, Qt::CaseInsensitive ) == 0 )
550 if ( !geometry.contains(
"coordinates" ) )
552 QgsDebugError( u
"JSON Point geometry must contain 'coordinates'"_s );
556 const json &coords = geometry[
"coordinates"];
559 else if ( type.compare(
"MultiPoint"_L1, Qt::CaseInsensitive ) == 0 )
561 if ( !geometry.contains(
"coordinates" ) )
563 QgsDebugError( u
"JSON MultiPoint geometry must contain 'coordinates'"_s );
567 const json &coords = geometry[
"coordinates"];
569 if ( !coords.is_array() )
571 QgsDebugError( u
"JSON MultiPoint geometry coordinates must be an array"_s );
575 auto multiPoint = std::make_unique< QgsMultiPoint >();
576 multiPoint->reserve(
static_cast< int >( coords.size() ) );
577 for (
const auto &pointCoords : coords )
584 multiPoint->addGeometry( point.release() );
589 else if ( type.compare(
"LineString"_L1, Qt::CaseInsensitive ) == 0 )
591 if ( !geometry.contains(
"coordinates" ) )
593 QgsDebugError( u
"JSON LineString geometry must contain 'coordinates'"_s );
597 const json &coords = geometry[
"coordinates"];
600 else if ( type.compare(
"MultiLineString"_L1, Qt::CaseInsensitive ) == 0 )
602 if ( !geometry.contains(
"coordinates" ) )
604 QgsDebugError( u
"JSON MultiLineString geometry must contain 'coordinates'"_s );
608 const json &coords = geometry[
"coordinates"];
610 if ( !coords.is_array() )
612 QgsDebugError( u
"JSON MultiLineString geometry coordinates must be an array"_s );
616 auto multiLineString = std::make_unique< QgsMultiLineString >();
617 multiLineString->reserve(
static_cast< int >( coords.size() ) );
618 for (
const auto &lineCoords : coords )
625 multiLineString->addGeometry( line.release() );
628 return multiLineString;
630 else if ( type.compare(
"Polygon"_L1, Qt::CaseInsensitive ) == 0 )
632 if ( !geometry.contains(
"coordinates" ) )
634 QgsDebugError( u
"JSON Polygon geometry must contain 'coordinates'"_s );
638 const json &coords = geometry[
"coordinates"];
639 if ( !coords.is_array() || coords.size() < 1 )
641 QgsDebugError( u
"JSON Polygon geometry coordinates must be an array of at least one ring"_s );
647 else if ( type.compare(
"MultiPolygon"_L1, Qt::CaseInsensitive ) == 0 )
649 if ( !geometry.contains(
"coordinates" ) )
651 QgsDebugError( u
"JSON MultiPolygon geometry must contain 'coordinates'"_s );
655 const json &coords = geometry[
"coordinates"];
657 if ( !coords.is_array() )
659 QgsDebugError( u
"JSON MultiPolygon geometry coordinates must be an array"_s );
663 auto multiPolygon = std::make_unique< QgsMultiPolygon >();
664 multiPolygon->reserve(
static_cast< int >( coords.size() ) );
665 for (
const auto &polygonCoords : coords )
672 multiPolygon->addGeometry( polygon.release() );
677 else if ( type.compare(
"GeometryCollection"_L1, Qt::CaseInsensitive ) == 0 )
679 if ( !geometry.contains(
"geometries" ) )
681 QgsDebugError( u
"JSON GeometryCollection geometry must contain 'geometries'"_s );
685 const json &geometries = geometry[
"geometries"];
687 if ( !geometries.is_array() )
689 QgsDebugError( u
"JSON GeometryCollection geometries must be an array"_s );
693 auto collection = std::make_unique< QgsGeometryCollection >();
694 collection->reserve(
static_cast< int >( geometries.size() ) );
695 for (
const auto &geometry : geometries )
702 collection->addGeometry(
object.release() );
708 QgsDebugError( u
"Unhandled GeoJSON geometry type: %1"_s.arg( type ) );
714 if ( !geometry.is_object() )
727 const auto jObj( json::parse( geometry.toStdString() ) );
730 catch ( json::parse_error &ex )
732 QgsDebugError( u
"Cannot parse json (%1): %2"_s.arg( geometry, ex.what() ) );
744 if ( val.userType() == QMetaType::Type::QVariantMap )
746 const QVariantMap &vMap = val.toMap();
747 json jMap = json::object();
748 for (
auto it = vMap.constBegin(); it != vMap.constEnd(); it++ )
754 else if ( val.userType() == QMetaType::Type::QVariantList || val.userType() == QMetaType::Type::QStringList )
756 const QVariantList &vList = val.toList();
757 json jList = json::array();
758 for (
const auto &v : vList )
766 switch ( val.userType() )
769 case QMetaType::UInt:
770 case QMetaType::LongLong:
771 case QMetaType::ULongLong:
772 j = val.toLongLong();
774 case QMetaType::Double:
775 case QMetaType::Float:
778 case QMetaType::Bool:
781 case QMetaType::QByteArray:
782 j = val.toByteArray().toBase64().toStdString();
785 j = val.toString().toStdString();
795 const QVariant res =
parseJson( jsonString, error );
797 if ( !error.isEmpty() )
800 QString::fromStdString( jsonString ) ) );
810 const json j = json::parse( jsonString );
813 catch ( json::parse_error &ex )
815 error = QString::fromStdString( ex.what() );
817 catch ( json::type_error &ex )
819 error = QString::fromStdString( ex.what() );
827 bool isPrimitive =
true;
829 std::function<QVariant( json )> _parser { [ & ]( json jObj ) -> QVariant {
831 if ( jObj.is_array() )
834 QVariantList results;
835 results.reserve( jObj.size() );
836 for (
const auto &item : jObj )
838 results.push_back( _parser( item ) );
842 else if ( jObj.is_object() )
846 for (
const auto &item : jObj.items() )
848 const auto key { QString::fromStdString( item.key() ) };
849 const auto value { _parser( item.value() ) };
850 results[ key ] = value;
856 if ( jObj.is_number_unsigned() )
860 const qulonglong num { jObj.get<qulonglong>() };
861 if ( num <= std::numeric_limits<int>::max() )
863 result =
static_cast<int>( num );
865 else if ( num <= std::numeric_limits<qlonglong>::max() )
867 result =
static_cast<qlonglong
>( num );
874 else if ( jObj.is_number_integer() )
876 const qlonglong num { jObj.get<qlonglong>() };
877 if ( num <= std::numeric_limits<int>::max() && num >= std::numeric_limits<int>::lowest() )
879 result =
static_cast<int>( num );
886 else if ( jObj.is_boolean() )
888 result = jObj.get<
bool>();
890 else if ( jObj.is_number_float() )
893 result = jObj.get<
double>();
895 else if ( jObj.is_string() )
897 if ( isPrimitive && jObj.get<std::string>().length() == 0 )
899 result = QString::fromStdString( jObj.get<std::string>() ).append(
"\"" ).insert( 0,
"\"" );
903 result = QString::fromStdString( jObj.get<std::string>() );
906 else if ( jObj.is_null() )
915 return _parser( value );
920 return jsonString.isEmpty() ? QVariant() :
parseJson( jsonString.toStdString() );
927 for (
int i = 0; i < fields.
count(); ++i )
931 if ( layer && useFieldFormatters )
936 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
947 if ( crs.
authid() ==
"OGC:CRS84" || crs.
authid() ==
"EPSG:4326" )
950 value[
"crs"][
"type"] =
"name";
951 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.
Represents a coordinate reference system (CRS).
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.
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.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
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.
int precision() const
Returns the maximum number of decimal places to use in geometry coordinates.
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.
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.
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 dataset.
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)