30 #include <QJsonDocument> 34 : mPrecision( precision )
35 , mLayer( vectorLayer )
39 mCrs = vectorLayer->
crs();
50 mCrs = vectorLayer->
crs();
72 const QVariant &
id )
const 75 QString s = QStringLiteral(
"{\n \"type\":\"Feature\",\n" );
81 if ( !geom.
isNull() && mIncludeGeometry )
88 if ( transformed.
transform( mTransform ) == 0 )
105 s += QLatin1String(
" \"geometry\":\n " );
106 s += geom.
asJson( mPrecision );
107 s += QLatin1String(
",\n" );
111 s += QLatin1String(
" \"geometry\":null,\n" );
116 int attributeCounter = 0;
117 if ( mIncludeAttributes || !extraProperties.isEmpty() )
121 if ( mIncludeAttributes )
125 QStringList formattersWhiteList;
126 formattersWhiteList << QStringLiteral(
"KeyValue" )
127 << QStringLiteral(
"List" )
128 << QStringLiteral(
"ValueRelation" )
129 << QStringLiteral(
"ValueMap" );
131 for (
int i = 0; i < fields.
count(); ++i )
133 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
136 if ( attributeCounter > 0 )
137 properties += QLatin1String(
",\n" );
144 if ( formattersWhiteList.contains( fieldFormatter->
id() ) )
148 QString name = fields.
at( i ).
name();
149 if ( mAttributeDisplayName )
151 name = mLayer->attributeDisplayName( i );
160 if ( !extraProperties.isEmpty() )
162 QVariantMap::const_iterator it = extraProperties.constBegin();
163 for ( ; it != extraProperties.constEnd(); ++it )
165 if ( attributeCounter > 0 )
166 properties += QLatin1String(
",\n" );
175 if ( mLayer && mIncludeRelatedAttributes )
178 Q_FOREACH (
const QgsRelation &relation, relations )
180 if ( attributeCounter > 0 )
181 properties += QLatin1String(
",\n" );
186 QString relatedFeatureAttributes;
190 QVector<QVariant> attributeWidgetCaches;
193 for (
const QgsField &field : fields )
197 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
202 int relationFeatures = 0;
205 if ( relationFeatures > 0 )
206 relatedFeatureAttributes += QLatin1String(
",\n" );
212 relatedFeatureAttributes.prepend(
'[' ).append(
']' );
214 properties += QStringLiteral(
" \"%1\":%2" ).arg( relation.
name(), relatedFeatureAttributes );
220 bool hasProperties = attributeCounter > 0;
222 s += QLatin1String(
" \"properties\":" );
226 s +=
"{\n" + properties +
"\n }\n";
230 s += QLatin1String(
"null\n" );
240 QStringList featureJSON;
241 Q_FOREACH (
const QgsFeature &feature, features )
246 return QStringLiteral(
"{ \"type\": \"FeatureCollection\",\n \"features\":[\n%1\n]}" ).arg( featureJSON.join( QStringLiteral(
",\n" ) ) );
267 if ( value.isNull() )
268 return QStringLiteral(
"null" );
270 switch ( value.type() )
274 case QVariant::LongLong:
275 case QVariant::ULongLong:
276 case QVariant::Double:
277 return value.toString();
280 return value.toBool() ?
"true" :
"false";
282 case QVariant::StringList:
285 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
288 case QVariant::String:
289 QString v = value.toString()
290 .replace(
'\\', QLatin1String(
"\\\\" ) )
291 .replace(
'"', QLatin1String(
"\\\"" ) )
292 .replace(
'\r', QLatin1String(
"\\r" ) )
293 .replace(
'\b', QLatin1String(
"\\b" ) )
294 .replace(
'\t', QLatin1String(
"\\t" ) )
295 .replace(
'/', QLatin1String(
"\\/" ) )
296 .replace(
'\n', QLatin1String(
"\\n" ) );
298 return v.prepend(
'"' ).append(
'"' );
306 for (
int i = 0; i < fields.
count(); ++i )
309 attrs += QLatin1String(
",\n" );
318 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
321 attrs += encodeValue( fields.
at( i ).
name() ) +
':' + encodeValue( val );
323 return attrs.prepend(
'{' ).append(
'}' );
328 QJsonParseError error;
329 const QJsonDocument jsonDoc = QJsonDocument::fromJson( json.toUtf8(), &error );
331 if ( error.error != QJsonParseError::NoError )
333 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( error.errorString(), json ) );
336 if ( !jsonDoc.isArray() )
338 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1) as array: %2" ).arg( error.errorString(), json ) );
341 Q_FOREACH (
const QJsonValue &cur, jsonDoc.array() )
343 QVariant curVariant = cur.toVariant();
344 if ( curVariant.convert( type ) )
345 result.append( curVariant );
347 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()
Gets the registry of available field formatters.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source CRS for feature geometries.
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
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
Gets the editor widget setup for the field.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
const QgsCoordinateReferenceSystem & crs
int count() const
Returns number of items.
QgsVectorLayer * vectorLayer() const
Returns the associated vector layer, if set.
QgsField at(int i) const
Gets 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 FINAL
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)...
QList< QgsRelation > referencedRelations(QgsVectorLayer *layer=nullptr) const
Gets 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...
Encapsulate a field in an attribute table or data source.
QgsFeatureRequest getRelatedFeaturesRequest(const QgsFeature &feature) const
Creates a request to return all the features on the referencing (child) layer which have a foreign ke...
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.
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).
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Query the layer for features specified in request.
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.
QgsCoordinateReferenceSystem crs
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.