QGIS API Documentation
3.16.0-Hannover (43b64b13f3)
|
Go to the documentation of this file.
31 #include <QJsonDocument>
33 #include <nlohmann/json.hpp>
37 , mLayer( vectorLayer )
74 const QVariant &
id,
int indent )
const
83 {
"type",
"Feature" },
88 auto intId =
id.toLongLong( &ok );
91 featureJson[
"id"] = intId;
95 featureJson[
"id"] =
id.toString().toStdString();
100 featureJson[
"id"] =
nullptr;
104 featureJson[
"id"] = feature.
id();
108 if ( !geom.
isNull() && mIncludeGeometry )
115 if ( mTransformGeometries && transformed.
transform( mTransform ) == 0 )
127 featureJson[
"bbox" ] =
135 featureJson[
"geometry" ] = geom.
asJsonObject( mPrecision );
139 featureJson[
"geometry" ] =
nullptr;
143 int attributeCounter { 0 };
145 if ( mIncludeAttributes || !extraProperties.isEmpty() )
148 if ( mIncludeAttributes )
152 QStringList formattersAllowList;
153 formattersAllowList << QStringLiteral(
"KeyValue" )
154 << QStringLiteral(
"List" )
155 << QStringLiteral(
"ValueRelation" )
156 << QStringLiteral(
"ValueMap" );
158 for (
int i = 0; i < fields.
count(); ++i )
160 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
169 if ( formattersAllowList.contains( fieldFormatter->
id() ) )
173 QString name = fields.
at( i ).
name();
174 if ( mAttributeDisplayName )
176 name = mLayer->attributeDisplayName( i );
183 if ( !extraProperties.isEmpty() )
185 QVariantMap::const_iterator it = extraProperties.constBegin();
186 for ( ; it != extraProperties.constEnd(); ++it )
194 if ( mLayer && mIncludeRelatedAttributes )
197 for (
const auto &relation : qgis::as_const( relations ) )
202 json relatedFeatureAttributes;
206 QVector<QVariant> attributeWidgetCaches;
213 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
222 properties[ relation.name().toStdString() ] = relatedFeatureAttributes;
227 featureJson[
"properties" ] = properties;
240 {
"type",
"FeatureCollection" },
241 {
"features", json::array() }
243 for (
const QgsFeature &feature : qgis::as_const( features ) )
257 encoding = QTextCodec::codecForName(
"UTF-8" );
265 encoding = QTextCodec::codecForName(
"UTF-8" );
272 if ( value.isNull() )
273 return QStringLiteral(
"null" );
275 switch ( value.type() )
279 case QVariant::LongLong:
280 case QVariant::ULongLong:
281 case QVariant::Double:
282 return value.toString();
285 return value.toBool() ?
"true" :
"false";
287 case QVariant::StringList:
290 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
293 case QVariant::String:
294 QString v = value.toString()
295 .replace(
'\\', QLatin1String(
"\\\\" ) )
296 .replace(
'"', QLatin1String(
"\\\"" ) )
297 .replace(
'\r', QLatin1String(
"\\r" ) )
298 .replace(
'\b', QLatin1String(
"\\b" ) )
299 .replace(
'\t', QLatin1String(
"\\t" ) )
300 .replace(
'/', QLatin1String(
"\\/" ) )
301 .replace(
'\n', QLatin1String(
"\\n" ) );
303 return v.prepend(
'"' ).append(
'"' );
311 for (
int i = 0; i < fields.
count(); ++i )
314 attrs += QLatin1String(
",\n" );
323 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
328 return attrs.prepend(
'{' ).append(
'}' );
333 QString errorMessage;
337 const auto jObj(
json::parse( json.toStdString() ) );
338 if ( ! jObj.is_array() )
340 throw json::parse_error::create( 0, 0, QStringLiteral(
"JSON value must be an array" ).toStdString() );
342 for (
const auto &item : jObj )
346 if ( item.is_number_integer() )
350 else if ( item.is_number_unsigned() )
352 v = item.get<
unsigned>();
354 else if ( item.is_number_float() )
357 v = item.get<
double>();
359 else if ( item.is_string() )
361 v = QString::fromStdString( item.get<std::string>() );
363 else if ( item.is_boolean() )
365 v = item.get<
bool>();
367 else if ( item.is_null() )
370 v = QVariant( type == QVariant::Type::Invalid ? QVariant::Type::Int : type );
374 if ( type != QVariant::Invalid )
376 if ( ! v.convert(
static_cast<int>( type ) ) )
378 QgsLogger::warning( QStringLiteral(
"Cannot convert json array element to specified type, ignoring: %1" ).arg( v.toString() ) );
382 result.push_back( v );
387 result.push_back( v );
391 catch ( json::parse_error &ex )
393 errorMessage = ex.what();
394 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( ex.what(), json ) );
402 if ( val.isNull() || ! val.isValid() )
407 if ( val.type() == QVariant::Type::Map )
409 const QVariantMap &vMap = val.toMap();
410 json jMap = json::object();
411 for (
auto it = vMap.constBegin(); it != vMap.constEnd(); it++ )
417 else if ( val.type() == QVariant::Type::List || val.type() == QVariant::Type::StringList )
419 const QVariantList &vList = val.toList();
420 json jList = json::array();
421 for (
const auto &v : vList )
429 switch ( val.userType() )
432 case QMetaType::UInt:
433 case QMetaType::LongLong:
434 case QMetaType::ULongLong:
435 j = val.toLongLong();
437 case QMetaType::Double:
438 case QMetaType::Float:
441 case QMetaType::Bool:
444 case QMetaType::QByteArray:
445 j = val.toByteArray().toBase64().toStdString();
448 j = val.toString().toStdString();
458 bool isPrimitive =
true;
460 std::function<QVariant( json )> _parser { [ & ]( json jObj ) -> QVariant {
462 if ( jObj.is_array() )
465 QVariantList results;
466 for (
const auto &item : jObj )
468 results.push_back( _parser( item ) );
472 else if ( jObj.is_object() )
476 for (
const auto &item : jObj.items() )
478 const auto key { QString::fromStdString( item.key() ) };
479 const auto value { _parser( item.value() ) };
480 results[ key ] = value;
486 if ( jObj.is_number_integer() )
488 result = jObj.get<
int>();
490 else if ( jObj.is_number_unsigned() )
492 result = jObj.get<
unsigned>();
494 else if ( jObj.is_boolean() )
496 result = jObj.get<
bool>();
498 else if ( jObj.is_number_float() )
501 result = jObj.get<
double>();
503 else if ( jObj.is_string() )
505 if ( isPrimitive && jObj.get<std::string>().length() == 0 )
507 result = QString::fromStdString( jObj.get<std::string>() ).append(
"\"" ).insert( 0,
"\"" );
511 result = QString::fromStdString( jObj.get<std::string>() );
514 else if ( jObj.is_null() )
528 catch ( json::parse_error &ex )
530 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( QString::fromStdString( ex.what() ),
531 QString::fromStdString( jsonString ) ) );
538 return parseJson( jsonString.toStdString() );
545 for (
int i = 0; i < fields.
count(); ++i )
554 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsRelationManager * relationManager
QgsCoordinateReferenceSystem crs
json exportFeaturesToJsonObject(const QgsFeatureList &features) const
Returns a JSON object representation of a list of features (feature collection).
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.
QgsVectorLayer * vectorLayer() const
Returns the associated vector layer, if set.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding=nullptr)
Attempts to retrieve the fields from a GeoJSON string representing a collection of features.
const QgsCoordinateReferenceSystem & crs
static Type flatType(Type type) SIP_HOLDGIL
Returns the flat type for a WKB type.
int count() const
Returns number of items.
Container of fields for a vector layer.
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
QString exportFeatures(const QgsFeatureList &features, int indent=-1) const
Returns a GeoJSON string representation of a list of features (feature collection).
json exportFeatureToJsonObject(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant()) const
Returns a QJsonObject representation of a feature.
static QgsProject * instance()
Returns the QgsProject singleton instance.
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a string representing a collection of features using OGR.
A rectangle specified with double values.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
This class wraps a request for features to a vector layer (or directly its vector data provider).
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a string representing a collection of features using OGR.
Custom exception class for Coordinate Reference System related exceptions.
static json exportAttributesToJsonObject(const QgsFeature &feature, QgsVectorLayer *layer=nullptr, const QVector< QVariant > &attributeWidgetCaches=QVector< QVariant >())
Exports all attributes from a QgsFeature as a json object.
QList< QgsRelation > referencedRelations(const QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
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 qgsRound(double number, int places)
Returns a double number, rounded (as close as possible) to the specified number of places.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source CRS for feature geometries.
QList< QgsFeature > QgsFeatureList
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static void warning(const QString &msg)
Goes to qWarning.
static QString encodeValue(const QVariant &value)
Encodes a value to a JSON string representation, adding appropriate quotations and escaping where req...
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
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.
This class represents a coordinate reference system (CRS).
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
virtual json asJsonObject(int precision=17) const
Exports the geometry to a json object.
void setVectorLayer(QgsVectorLayer *vectorLayer)
Sets the associated vector layer (required for related attribute export).
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source CRS for feature geometries.
bool nextFeature(QgsFeature &f)
A geometry is the spatial representation of a feature.
Represents a vector layer which manages a vector based data sets.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
QgsJsonExporter(QgsVectorLayer *vectorLayer=nullptr, int precision=6)
Constructor for QgsJsonExporter.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
Wrapper for iterator of features from vector data provider or vector layer.
static json jsonFromVariant(const QVariant &v)
Converts a QVariant v to a json object.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields=QgsFields(), QTextCodec *encoding=nullptr)
Attempts to parse a GeoJSON string to a collection of features.
static QVariantList parseArray(const QString &json, QVariant::Type type=QVariant::Invalid)
Parse a simple array (depth=1)
QgsSQLStatement::Node * parse(const QString &str, QString &parserErrorMsg, bool allowFragments)
QgsWkbTypes::Type wkbType() const SIP_HOLDGIL
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned.
Encapsulate a field in an attribute table or data source.