29 #include <QJsonDocument> 33 : mPrecision( precision )
34 , mLayer( vectorLayer )
38 mCrs = vectorLayer->
crs();
49 mCrs = vectorLayer->
crs();
71 const QVariant &
id )
const 74 QString s = QStringLiteral(
"{\n \"type\":\"Feature\",\n" );
80 if ( !geom.
isNull() && mIncludeGeometry )
87 if ( transformed.
transform( mTransform ) == 0 )
104 s += QLatin1String(
" \"geometry\":\n " );
105 s += geom.
asJson( mPrecision );
106 s += QLatin1String(
",\n" );
110 s += QLatin1String(
" \"geometry\":null,\n" );
115 int attributeCounter = 0;
116 if ( mIncludeAttributes || !extraProperties.isEmpty() )
120 if ( mIncludeAttributes )
124 QStringList formattersWhiteList;
125 formattersWhiteList << QStringLiteral(
"KeyValue" )
126 << QStringLiteral(
"List" )
127 << QStringLiteral(
"ValueRelation" )
128 << QStringLiteral(
"ValueMap" );
130 for (
int i = 0; i < fields.
count(); ++i )
132 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
135 if ( attributeCounter > 0 )
136 properties += QLatin1String(
",\n" );
143 if ( formattersWhiteList.contains( fieldFormatter->
id() ) )
153 if ( !extraProperties.isEmpty() )
155 QVariantMap::const_iterator it = extraProperties.constBegin();
156 for ( ; it != extraProperties.constEnd(); ++it )
158 if ( attributeCounter > 0 )
159 properties += QLatin1String(
",\n" );
168 if ( mLayer && mIncludeRelatedAttributes )
171 Q_FOREACH (
const QgsRelation &relation, relations )
173 if ( attributeCounter > 0 )
174 properties += QLatin1String(
",\n" );
179 QString relatedFeatureAttributes;
183 QVector<QVariant> attributeWidgetCaches;
186 for (
const QgsField &field : fields )
190 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
195 int relationFeatures = 0;
198 if ( relationFeatures > 0 )
199 relatedFeatureAttributes += QLatin1String(
",\n" );
205 relatedFeatureAttributes.prepend(
'[' ).append(
']' );
207 properties += QStringLiteral(
" \"%1\":%2" ).arg( relation.
name(), relatedFeatureAttributes );
213 bool hasProperties = attributeCounter > 0;
215 s += QLatin1String(
" \"properties\":" );
219 s +=
"{\n" + properties +
"\n }\n";
223 s += QLatin1String(
"null\n" );
233 QStringList featureJSON;
234 Q_FOREACH (
const QgsFeature &feature, features )
239 return QStringLiteral(
"{ \"type\": \"FeatureCollection\",\n \"features\":[\n%1\n]}" ).arg( featureJSON.join( QStringLiteral(
",\n" ) ) );
260 if ( value.isNull() )
261 return QStringLiteral(
"null" );
263 switch ( value.type() )
267 case QVariant::LongLong:
268 case QVariant::ULongLong:
269 case QVariant::Double:
270 return value.toString();
273 return value.toBool() ?
"true" :
"false";
275 case QVariant::StringList:
278 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
281 case QVariant::String:
282 QString v = value.toString()
283 .replace(
'\\', QLatin1String(
"\\\\" ) )
284 .replace(
'"', QLatin1String(
"\\\"" ) )
285 .replace(
'\r', QLatin1String(
"\\r" ) )
286 .replace(
'\b', QLatin1String(
"\\b" ) )
287 .replace(
'\t', QLatin1String(
"\\t" ) )
288 .replace(
'/', QLatin1String(
"\\/" ) )
289 .replace(
'\n', QLatin1String(
"\\n" ) );
291 return v.prepend(
'"' ).append(
'"' );
299 for (
int i = 0; i < fields.
count(); ++i )
302 attrs += QLatin1String(
",\n" );
311 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
314 attrs += encodeValue( fields.
at( i ).
name() ) +
':' + encodeValue( val );
316 return attrs.prepend(
'{' ).append(
'}' );
321 QJsonParseError error;
322 const QJsonDocument jsonDoc = QJsonDocument::fromJson( json.toUtf8(), &error );
324 if ( error.error != QJsonParseError::NoError )
326 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( error.errorString(), json ) );
329 if ( !jsonDoc.isArray() )
331 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1) as array: %2" ).arg( error.errorString(), json ) );
334 Q_FOREACH (
const QJsonValue &cur, jsonDoc.array() )
336 QVariant curVariant = cur.toVariant();
337 if ( curVariant.convert( type ) )
338 result.append( curVariant );
340 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.
bool isNull() const
Returns true if the geometry is null (ie, contains no underlying geometry accessible via geometry() )...
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.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
void setVectorLayer(QgsVectorLayer *vectorLayer)
Sets the associated vector layer (required for related attribute export).
QList< QgsFeature > QgsFeatureList
static void warning(const QString &msg)
Goes to qWarning.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source CRS for feature geometries.
QgsVectorLayer referencingLayer
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
const QgsCoordinateReferenceSystem & crs
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
QString exportFeatures(const QgsFeatureList &features) const
Returns a GeoJSON string representation of a list of features (feature collection).
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.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
static QString encodeValue(const QVariant &value)
Encodes a value to a JSON string representation, adding appropriate quotations and escaping where req...
double xMaximum() const
Returns the x maximum value (right side of rectangle).
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)...
QString asJson(int precision=17) const
Exports the geometry to a GeoJSON string.
int count() const
Returns number of items.
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.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source CRS for feature geometries.
QgsRelationManager relationManager
QgsFeatureRequest getRelatedFeaturesRequest(const QgsFeature &feature) const
Creates a request to return all the features on the referencing (child) layer which have a foreign ke...
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.
QgsJsonExporter(QgsVectorLayer *vectorLayer=nullptr, int precision=6)
Constructor for QgsJsonExporter.
QString exportFeature(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant()) const
Returns a GeoJSON string representation of a feature.
QList< QgsRelation > referencedRelations(QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static QgsProject * instance()
Returns the QgsProject singleton instance.
This class represents a coordinate reference system (CRS).
static QVariantList parseArray(const QString &json, QVariant::Type type)
Parse a simple array (depth=1).
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.
QgsVectorLayer * vectorLayer() const
Returns the associated vector layer, if set.
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.
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
static Type flatType(Type type)
Returns the flat type for a WKB type.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
QgsCoordinateReferenceSystem crs
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.