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 );
95 catch ( json::type_error &ex )
100 catch ( json::other_error &ex )
110 {
"type",
"Feature" },
114 if ( !extraMembers.isEmpty() )
116 QVariantMap::const_iterator it = extraMembers.constBegin();
117 for ( ; it != extraMembers.constEnd(); ++it )
126 auto intId =
id.toLongLong( &ok );
129 featureJson[
"id"] = intId;
133 featureJson[
"id"] =
id.toString().toStdString();
138 featureJson[
"id"] =
nullptr;
142 featureJson[
"id"] = feature.
id();
146 if ( !geom.
isNull() && mIncludeGeometry )
148 if ( mCrs.isValid() )
167 featureJson[
"geometry"] = geom.
asJsonObject( mPrecision );
171 featureJson[
"geometry"] =
nullptr;
176 if ( mIncludeAttributes || !extraProperties.isEmpty() )
179 if ( mIncludeAttributes )
183 QStringList formattersAllowList;
184 formattersAllowList << u
"KeyValue"_s << u
"List"_s << u
"ValueRelation"_s << u
"ValueMap"_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;
263 json data { {
"type",
"FeatureCollection" }, {
"features", json::array() } };
267 for (
const QgsFeature &feature : std::as_const( features ) )
276 mDestinationCrs = destinationCrs;
277 mTransform.setDestinationCrs( mDestinationCrs );
287 encoding = QTextCodec::codecForName(
"UTF-8" );
295 encoding = QTextCodec::codecForName(
"UTF-8" );
305 switch ( value.userType() )
307 case QMetaType::Type::Int:
308 case QMetaType::Type::UInt:
309 case QMetaType::Type::LongLong:
310 case QMetaType::Type::ULongLong:
311 case QMetaType::Type::Double:
312 return value.toString();
314 case QMetaType::Type::Bool:
315 return value.toBool() ?
"true" :
"false";
317 case QMetaType::Type::QStringList:
318 case QMetaType::Type::QVariantList:
319 case QMetaType::Type::QVariantMap:
320 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
323 case QMetaType::Type::QString:
325 = value.toString().replace(
'\\',
"\\\\"_L1 ).replace(
'"',
"\\\""_L1 ).replace(
'\r',
"\\r"_L1 ).replace(
'\b',
"\\b"_L1 ).replace(
'\t',
"\\t"_L1 ).replace(
'/',
"\\/"_L1 ).replace(
'\n',
"\\n"_L1 );
327 return v.prepend(
'"' ).append(
'"' );
335 for (
int i = 0; i < fields.
count(); ++i )
347 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
352 return attrs.prepend(
'{' ).
append(
'}' );
357 QString errorMessage;
361 const auto jObj( json::parse( json.toStdString() ) );
362 if ( !jObj.is_array() )
364 throw json::parse_error::create( 0, 0, u
"JSON value must be an array"_s.toStdString(), &jObj );
366 for (
const auto &item : jObj )
370 if ( item.is_number_integer() )
374 else if ( item.is_number_unsigned() )
376 v = item.get<
unsigned>();
378 else if ( item.is_number_float() )
381 v = item.get<
double>();
383 else if ( item.is_string() )
385 v = QString::fromStdString( item.get<std::string>() );
387 else if ( item.is_boolean() )
389 v = item.get<
bool>();
391 else if ( item.is_null() )
398 if ( type != QMetaType::Type::UnknownType )
400 if ( !v.convert(
static_cast<int>( type ) ) )
402 QgsLogger::warning( u
"Cannot convert json array element to specified type, ignoring: %1"_s.arg( v.toString() ) );
406 result.push_back( v );
411 result.push_back( v );
415 catch ( json::parse_error &ex )
417 errorMessage = ex.what();
431 if ( !coords.is_array() || coords.size() < 2 || coords.size() > 3 )
433 QgsDebugError( u
"JSON Point geometry coordinates must be an array of two or three numbers"_s );
437 const double x = coords[0].get<
double >();
438 const double y = coords[1].get<
double >();
439 if ( coords.size() == 2 )
441 return std::make_unique< QgsPoint >( x, y );
445 const double z = coords[2].get<
double >();
446 return std::make_unique< QgsPoint >( x, y, z );
452 if ( !coords.is_array() || coords.size() < 2 )
454 QgsDebugError( u
"JSON LineString geometry coordinates must be an array of at least two points"_s );
458 const std::size_t coordsSize = coords.size();
463 x.resize( coordsSize );
464 y.resize( coordsSize );
465 z.resize( coordsSize );
467 double *xOut = x.data();
468 double *yOut = y.data();
469 double *zOut = z.data();
471 for (
const auto &coord : coords )
473 if ( !coord.is_array() || coord.size() < 2 || coord.size() > 3 )
475 QgsDebugError( u
"JSON LineString geometry coordinates must be an array of two or three numbers"_s );
479 *xOut++ = coord[0].get<
double >();
480 *yOut++ = coord[1].get<
double >();
481 if ( coord.size() == 3 )
483 *zOut++ = coord[2].get<
double >();
488 *zOut++ = std::numeric_limits< double >::quiet_NaN();
492 return std::make_unique< QgsLineString >( x, y, hasZ ? z : QVector<double>() );
497 if ( !coords.is_array() || coords.size() < 1 )
499 QgsDebugError( u
"JSON Polygon geometry coordinates must be an array"_s );
503 const std::size_t coordsSize = coords.size();
510 auto polygon = std::make_unique< QgsPolygon >( exterior.release() );
511 for ( std::size_t i = 1; i < coordsSize; ++i )
518 polygon->addInteriorRing( ring.release() );
525 if ( !geometry.is_object() )
531 if ( !geometry.contains(
"type" ) )
537 const QString type = QString::fromStdString( geometry[
"type"].get< std::string >() );
538 if ( type.compare(
"Point"_L1, Qt::CaseInsensitive ) == 0 )
540 if ( !geometry.contains(
"coordinates" ) )
542 QgsDebugError( u
"JSON Point geometry must contain 'coordinates'"_s );
546 const json &coords = geometry[
"coordinates"];
549 else if ( type.compare(
"MultiPoint"_L1, Qt::CaseInsensitive ) == 0 )
551 if ( !geometry.contains(
"coordinates" ) )
553 QgsDebugError( u
"JSON MultiPoint geometry must contain 'coordinates'"_s );
557 const json &coords = geometry[
"coordinates"];
559 if ( !coords.is_array() )
561 QgsDebugError( u
"JSON MultiPoint geometry coordinates must be an array"_s );
565 auto multiPoint = std::make_unique< QgsMultiPoint >();
566 multiPoint->reserve(
static_cast< int >( coords.size() ) );
567 for (
const auto &pointCoords : coords )
574 multiPoint->addGeometry( point.release() );
579 else if ( type.compare(
"LineString"_L1, Qt::CaseInsensitive ) == 0 )
581 if ( !geometry.contains(
"coordinates" ) )
583 QgsDebugError( u
"JSON LineString geometry must contain 'coordinates'"_s );
587 const json &coords = geometry[
"coordinates"];
590 else if ( type.compare(
"MultiLineString"_L1, Qt::CaseInsensitive ) == 0 )
592 if ( !geometry.contains(
"coordinates" ) )
594 QgsDebugError( u
"JSON MultiLineString geometry must contain 'coordinates'"_s );
598 const json &coords = geometry[
"coordinates"];
600 if ( !coords.is_array() )
602 QgsDebugError( u
"JSON MultiLineString geometry coordinates must be an array"_s );
606 auto multiLineString = std::make_unique< QgsMultiLineString >();
607 multiLineString->reserve(
static_cast< int >( coords.size() ) );
608 for (
const auto &lineCoords : coords )
615 multiLineString->addGeometry( line.release() );
618 return multiLineString;
620 else if ( type.compare(
"Polygon"_L1, Qt::CaseInsensitive ) == 0 )
622 if ( !geometry.contains(
"coordinates" ) )
624 QgsDebugError( u
"JSON Polygon geometry must contain 'coordinates'"_s );
628 const json &coords = geometry[
"coordinates"];
629 if ( !coords.is_array() || coords.size() < 1 )
631 QgsDebugError( u
"JSON Polygon geometry coordinates must be an array of at least one ring"_s );
637 else if ( type.compare(
"MultiPolygon"_L1, Qt::CaseInsensitive ) == 0 )
639 if ( !geometry.contains(
"coordinates" ) )
641 QgsDebugError( u
"JSON MultiPolygon geometry must contain 'coordinates'"_s );
645 const json &coords = geometry[
"coordinates"];
647 if ( !coords.is_array() )
649 QgsDebugError( u
"JSON MultiPolygon geometry coordinates must be an array"_s );
653 auto multiPolygon = std::make_unique< QgsMultiPolygon >();
654 multiPolygon->reserve(
static_cast< int >( coords.size() ) );
655 for (
const auto &polygonCoords : coords )
662 multiPolygon->addGeometry( polygon.release() );
667 else if ( type.compare(
"GeometryCollection"_L1, Qt::CaseInsensitive ) == 0 )
669 if ( !geometry.contains(
"geometries" ) )
671 QgsDebugError( u
"JSON GeometryCollection geometry must contain 'geometries'"_s );
675 const json &geometries = geometry[
"geometries"];
677 if ( !geometries.is_array() )
679 QgsDebugError( u
"JSON GeometryCollection geometries must be an array"_s );
683 auto collection = std::make_unique< QgsGeometryCollection >();
684 collection->reserve(
static_cast< int >( geometries.size() ) );
685 for (
const auto &geometry : geometries )
692 collection->addGeometry(
object.release() );
698 QgsDebugError( u
"Unhandled GeoJSON geometry type: %1"_s.arg( type ) );
704 if ( !geometry.is_object() )
717 const auto jObj( json::parse( geometry.toStdString() ) );
720 catch ( json::parse_error &ex )
722 QgsDebugError( u
"Cannot parse json (%1): %2"_s.arg( geometry, ex.what() ) );
734 if ( val.userType() == QMetaType::Type::QVariantMap )
736 const QVariantMap &vMap = val.toMap();
737 json jMap = json::object();
738 for (
auto it = vMap.constBegin(); it != vMap.constEnd(); it++ )
744 else if ( val.userType() == QMetaType::Type::QVariantList || val.userType() == QMetaType::Type::QStringList )
746 const QVariantList &vList = val.toList();
747 json jList = json::array();
748 for (
const auto &v : vList )
756 switch ( val.userType() )
759 case QMetaType::UInt:
760 case QMetaType::LongLong:
761 case QMetaType::ULongLong:
762 j = val.toLongLong();
764 case QMetaType::Double:
765 case QMetaType::Float:
768 case QMetaType::Bool:
771 case QMetaType::QByteArray:
772 j = val.toByteArray().toBase64().toStdString();
775 j = val.toString().toStdString();
785 const QVariant res =
parseJson( jsonString, error );
787 if ( !error.isEmpty() )
789 QgsLogger::warning( u
"Cannot parse json (%1): %2"_s.arg( error, QString::fromStdString( jsonString ) ) );
799 const json j = json::parse( jsonString );
802 catch ( json::parse_error &ex )
804 error = QString::fromStdString( ex.what() );
806 catch ( json::type_error &ex )
808 error = QString::fromStdString( ex.what() );
816 bool isPrimitive =
true;
818 std::function<QVariant( json )> _parser { [&]( json jObj ) -> QVariant {
820 if ( jObj.is_array() )
823 QVariantList results;
824 results.reserve( jObj.size() );
825 for (
const auto &item : jObj )
827 results.push_back( _parser( item ) );
831 else if ( jObj.is_object() )
835 for (
const auto &item : jObj.items() )
837 const auto key { QString::fromStdString( item.key() ) };
838 const auto value { _parser( item.value() ) };
839 results[key] = value;
845 if ( jObj.is_number_unsigned() )
849 const qulonglong num { jObj.get<qulonglong>() };
850 if ( num <= std::numeric_limits<int>::max() )
852 result =
static_cast<int>( num );
854 else if ( num <= std::numeric_limits<qlonglong>::max() )
856 result =
static_cast<qlonglong
>( num );
863 else if ( jObj.is_number_integer() )
865 const qlonglong num { jObj.get<qlonglong>() };
866 if ( num <= std::numeric_limits<int>::max() && num >= std::numeric_limits<int>::lowest() )
868 result =
static_cast<int>( num );
875 else if ( jObj.is_boolean() )
877 result = jObj.get<
bool>();
879 else if ( jObj.is_number_float() )
882 result = jObj.get<
double>();
884 else if ( jObj.is_string() )
886 if ( isPrimitive && jObj.get<std::string>().length() == 0 )
888 result = QString::fromStdString( jObj.get<std::string>() ).append(
"\"" ).insert( 0,
"\"" );
892 result = QString::fromStdString( jObj.get<std::string>() );
895 else if ( jObj.is_null() )
903 return _parser( value );
908 return jsonString.isEmpty() ? QVariant() :
parseJson( jsonString.toStdString() );
915 for (
int i = 0; i < fields.
count(); ++i )
919 if ( layer && useFieldFormatters )
924 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
935 if ( crs.
authid() ==
"OGC:CRS84" || crs.
authid() ==
"EPSG:4326" )
938 value[
"crs"][
"type"] =
"name";
939 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 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.
QString exportFeature(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant(), int indent=-1, const QVariantMap &extraMembers=QVariantMap()) const
Returns a GeoJSON string representation of a feature.
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.
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.
json exportFeatureToJsonObject(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant(), const QVariantMap &extraMembers=QVariantMap()) const
Returns a QJsonObject representation of a feature.
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)