29 #include <QJsonDocument> 33 : mPrecision( precision )
34 , mLayer( vectorLayer )
38 mCrs = vectorLayer->
crs();
49 mCrs = vectorLayer->
crs();
71 const QVariant &
id )
const 73 QString s = QStringLiteral(
"{\n \"type\":\"Feature\",\n" );
79 if ( !geom.
isNull() && mIncludeGeometry )
86 if ( transformed.
transform( mTransform ) == 0 )
103 s += QLatin1String(
" \"geometry\":\n " );
104 s += geom.
asJson( mPrecision );
105 s += QLatin1String(
",\n" );
109 s += QLatin1String(
" \"geometry\":null,\n" );
114 int attributeCounter = 0;
115 if ( mIncludeAttributes || !extraProperties.isEmpty() )
119 if ( mIncludeAttributes )
123 for (
int i = 0; i < fields.
count(); ++i )
125 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
128 if ( attributeCounter > 0 )
129 properties += QLatin1String(
",\n" );
146 if ( !extraProperties.isEmpty() )
148 QVariantMap::const_iterator it = extraProperties.constBegin();
149 for ( ; it != extraProperties.constEnd(); ++it )
151 if ( attributeCounter > 0 )
152 properties += QLatin1String(
",\n" );
161 if ( mLayer && mIncludeRelatedAttributes )
164 Q_FOREACH (
const QgsRelation &relation, relations )
166 if ( attributeCounter > 0 )
167 properties += QLatin1String(
",\n" );
172 QString relatedFeatureAttributes;
176 QVector<QVariant> attributeWidgetCaches;
178 for (
const auto &field : childLayer->
fields() )
182 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
187 int relationFeatures = 0;
190 if ( relationFeatures > 0 )
191 relatedFeatureAttributes += QLatin1String(
",\n" );
197 relatedFeatureAttributes.prepend(
'[' ).append(
']' );
199 properties += QStringLiteral(
" \"%1\":%2" ).arg( relation.
name(), relatedFeatureAttributes );
205 bool hasProperties = attributeCounter > 0;
207 s += QLatin1String(
" \"properties\":" );
211 s +=
"{\n" + properties +
"\n }\n";
215 s += QLatin1String(
"null\n" );
225 QStringList featureJSON;
226 Q_FOREACH (
const QgsFeature &feature, features )
231 return QStringLiteral(
"{ \"type\": \"FeatureCollection\",\n \"features\":[\n%1\n]}" ).arg( featureJSON.join( QStringLiteral(
",\n" ) ) );
252 if ( value.isNull() )
253 return QStringLiteral(
"null" );
255 switch ( value.type() )
259 case QVariant::LongLong:
260 case QVariant::ULongLong:
261 case QVariant::Double:
262 return value.toString();
265 return value.toBool() ?
"true" :
"false";
267 case QVariant::StringList:
270 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
273 case QVariant::String:
274 QString v = value.toString()
275 .replace(
'\\', QLatin1String(
"\\\\" ) )
276 .replace(
'"', QLatin1String(
"\\\"" ) )
277 .replace(
'\r', QLatin1String(
"\\r" ) )
278 .replace(
'\b', QLatin1String(
"\\b" ) )
279 .replace(
'\t', QLatin1String(
"\\t" ) )
280 .replace(
'/', QLatin1String(
"\\/" ) )
281 .replace(
'\n', QLatin1String(
"\\n" ) );
283 return v.prepend(
'"' ).append(
'"' );
291 for (
int i = 0; i < fields.
count(); ++i )
294 attrs += QLatin1String(
",\n" );
303 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
306 attrs += encodeValue( fields.
at( i ).
name() ) +
':' + encodeValue( val );
308 return attrs.prepend(
'{' ).append(
'}' );
313 QJsonParseError error;
314 const QJsonDocument jsonDoc = QJsonDocument::fromJson( json.toUtf8(), &error );
316 if ( error.error != QJsonParseError::NoError )
318 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( error.errorString(), json ) );
321 if ( !jsonDoc.isArray() )
323 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1) as array: %2" ).arg( error.errorString(), json ) );
326 Q_FOREACH (
const QJsonValue &cur, jsonDoc.array() )
328 QVariant curVariant = cur.toVariant();
329 if ( curVariant.convert( type ) )
330 result.append( curVariant );
332 QgsLogger::warning( QStringLiteral(
"Cannot convert json array element: %1" ).arg( cur.toString() ) );
Wrapper for iterator of features from vector data provider or vector layer.
A rectangle specified with double values.
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Get the registry of available field formatters.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source CRS for feature geometries.
bool isNull() const
Returns true if the geometry is null (ie, contains no underlying geometry accessible via geometry() )...
void setVectorLayer(QgsVectorLayer *vectorLayer)
Sets the associated vector layer (required for related attribute export).
QList< QgsFeature > QgsFeatureList
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static void warning(const QString &msg)
Goes to qWarning.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source CRS for feature geometries.
QString asJson(int precision=17) const
Exports the geometry to a GeoJSON string.
QgsVectorLayer referencingLayer
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
QgsEditorWidgetSetup editorWidgetSetup() const
Get the editor widget setup for the field.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
int count() const
Return number of items.
QgsVectorLayer * vectorLayer() const
Returns the associated vector layer, if set.
QgsField at(int i) const
Get field at particular index (must be in range 0..N-1)
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a string representing a collection of features using OGR.
QgsFields fields() const override
Returns the list of fields of this layer.
static QString encodeValue(const QVariant &value)
Encodes a value to a JSON string representation, adding appropriate quotations and escaping where req...
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a GeoJSON string representing a collection of features...
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
QgsCoordinateReferenceSystem crs() const
Returns the layer's spatial reference system.
QList< QgsRelation > referencedRelations(QgsVectorLayer *layer=nullptr) const
Get all relations where this layer is the referenced part (i.e.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a string representing a collection of features using OGR...
QgsFeatureRequest getRelatedFeaturesRequest(const QgsFeature &feature) const
Creates a request to return all the features on the referencing (child) layer which have a foreign ke...
QgsGeometry geometry() const
Returns the geometry associated with this feature.
QgsRelationManager relationManager
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a GeoJSON string to a collection of features.
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.
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const override
Query the layer for features specified in request.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
QgsJsonExporter(QgsVectorLayer *vectorLayer=nullptr, int precision=6)
Constructor for QgsJsonExporter.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
QString exportFeatures(const QgsFeatureList &features) const
Returns a GeoJSON string representation of a list of features (feature collection).
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
This class represents a coordinate reference system (CRS).
static QVariantList parseArray(const QString &json, QVariant::Type type)
Parse a simple array (depth=1).
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Custom exception class for Coordinate Reference System related exceptions.
QString exportFeature(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant()) const
Returns a GeoJSON string representation of a feature.
bool nextFeature(QgsFeature &f)
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Represents a vector layer which manages a vector based data sets.
static Type flatType(Type type)
Returns the flat type for a WKB type.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Set flags that affect how features will be fetched.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.