QGIS API Documentation
3.14.0-Pi (9f7028fd23)
|
Go to the documentation of this file.
30 #include <QJsonDocument>
32 #include <nlohmann/json.hpp>
36 , mLayer( vectorLayer )
73 const QVariant &
id,
int indent )
const
82 {
"type",
"Feature" },
87 auto intId =
id.toLongLong( &ok );
90 featureJson[
"id"] = intId;
94 featureJson[
"id"] =
id.toString().toStdString();
99 featureJson[
"id"] = feature.
id();
103 if ( !geom.
isNull() && mIncludeGeometry )
110 if ( mTransformGeometries && transformed.
transform( mTransform ) == 0 )
122 featureJson[
"bbox" ] =
130 featureJson[
"geometry" ] = geom.
asJsonObject( mPrecision );
134 featureJson[
"geometry" ] =
nullptr;
138 int attributeCounter { 0 };
140 if ( mIncludeAttributes || !extraProperties.isEmpty() )
143 if ( mIncludeAttributes )
147 QStringList formattersAllowList;
148 formattersAllowList << QStringLiteral(
"KeyValue" )
149 << QStringLiteral(
"List" )
150 << QStringLiteral(
"ValueRelation" )
151 << QStringLiteral(
"ValueMap" );
153 for (
int i = 0; i < fields.
count(); ++i )
155 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
164 if ( formattersAllowList.contains( fieldFormatter->
id() ) )
168 QString name = fields.
at( i ).
name();
169 if ( mAttributeDisplayName )
171 name = mLayer->attributeDisplayName( i );
178 if ( !extraProperties.isEmpty() )
180 QVariantMap::const_iterator it = extraProperties.constBegin();
181 for ( ; it != extraProperties.constEnd(); ++it )
189 if ( mLayer && mIncludeRelatedAttributes )
192 for (
const auto &relation : qgis::as_const( relations ) )
197 json relatedFeatureAttributes;
201 QVector<QVariant> attributeWidgetCaches;
204 for (
const QgsField &field : fields )
208 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
217 properties[ relation.name().toStdString() ] = relatedFeatureAttributes;
222 featureJson[
"properties" ] = properties;
235 {
"type",
"FeatureCollection" },
236 {
"features", json::array() }
238 for (
const QgsFeature &feature : qgis::as_const( features ) )
252 encoding = QTextCodec::codecForName(
"UTF-8" );
260 encoding = QTextCodec::codecForName(
"UTF-8" );
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 );
323 return attrs.prepend(
'{' ).append(
'}' );
328 QString errorMessage;
332 const auto jObj(
json::parse( json.toStdString() ) );
333 if ( ! jObj.is_array() )
335 throw json::parse_error::create( 0, 0, QStringLiteral(
"JSON value must be an array" ).toStdString() );
337 for (
const auto &item : jObj )
341 if ( item.is_number_integer() )
345 else if ( item.is_number_unsigned() )
347 v = item.get<
unsigned>();
349 else if ( item.is_number_float() )
352 v = item.get<
double>();
354 else if ( item.is_string() )
356 v = QString::fromStdString( item.get<std::string>() );
358 else if ( item.is_boolean() )
360 v = item.get<
bool>();
362 else if ( item.is_null() )
365 v = QVariant( type == QVariant::Type::Invalid ? QVariant::Type::Int : type );
369 if ( type != QVariant::Invalid )
371 if ( ! v.convert(
static_cast<int>( type ) ) )
373 QgsLogger::warning( QStringLiteral(
"Cannot convert json array element to specified type, ignoring: %1" ).arg( v.toString() ) );
377 result.push_back( v );
382 result.push_back( v );
386 catch ( json::parse_error &ex )
388 errorMessage = ex.what();
389 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( ex.what(), json ) );
397 if ( val.isNull() || ! val.isValid() )
402 if ( val.type() == QVariant::Type::Map )
404 const QVariantMap &vMap = val.toMap();
405 json jMap = json::object();
406 for (
auto it = vMap.constBegin(); it != vMap.constEnd(); it++ )
412 else if ( val.type() == QVariant::Type::List || val.type() == QVariant::Type::StringList )
414 const QVariantList &vList = val.toList();
415 json jList = json::array();
416 for (
const auto &v : vList )
424 switch ( val.userType() )
427 case QMetaType::UInt:
428 case QMetaType::LongLong:
429 case QMetaType::ULongLong:
430 j = val.toLongLong();
432 case QMetaType::Double:
433 case QMetaType::Float:
436 case QMetaType::Bool:
439 case QMetaType::QByteArray:
440 j = val.toByteArray().toBase64().toStdString();
443 j = val.toString().toStdString();
453 bool isPrimitive =
true;
455 std::function<QVariant( json )> _parser { [ & ]( json jObj ) -> QVariant {
457 if ( jObj.is_array() )
460 QVariantList results;
461 for (
const auto &item : jObj )
463 results.push_back( _parser( item ) );
467 else if ( jObj.is_object() )
471 for (
const auto &item : jObj.items() )
473 const auto key { QString::fromStdString( item.key() ) };
474 const auto value { _parser( item.value() ) };
475 results[ key ] = value;
481 if ( jObj.is_number_integer() )
483 result = jObj.get<
int>();
485 else if ( jObj.is_number_unsigned() )
487 result = jObj.get<
unsigned>();
489 else if ( jObj.is_boolean() )
491 result = jObj.get<
bool>();
493 else if ( jObj.is_number_float() )
496 result = jObj.get<
double>();
498 else if ( jObj.is_string() )
500 if ( isPrimitive && jObj.get<std::string>().length() == 0 )
502 result = QString::fromStdString( jObj.get<std::string>() ).append(
"\"" ).insert( 0,
"\"" );
506 result = QString::fromStdString( jObj.get<std::string>() );
509 else if ( jObj.is_null() )
523 catch ( json::parse_error &ex )
525 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( QString::fromStdString( ex.what() ),
526 QString::fromStdString( jsonString ) ) );
533 return parseJson( jsonString.toStdString() );
540 for (
int i = 0; i < fields.
count(); ++i )
549 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
double xMaximum() const
Returns the x maximum value (right side of rectangle).
int count() const
Returns number of items.
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.
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
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.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a string representing a collection of features using OGR.
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...
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.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
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).
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source CRS for feature geometries.
bool nextFeature(QgsFeature &f)
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
QgsJsonExporter(QgsVectorLayer *vectorLayer=nullptr, int precision=6)
Constructor for QgsJsonExporter.
QgsSQLStatement::Node * parse(const QString &str, QString &parserErrorMsg)
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)
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)
double xMinimum() const
Returns the x minimum value (left side of rectangle).
static Type flatType(Type type)
Returns the flat type for a WKB type.
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned.